Skip to content

fix(merge-review): accept Codex review receipts at the exact head - #651

Draft
frankxai wants to merge 1 commit into
mainfrom
agent/opencode/gate-codex-receipt
Draft

frankxai wants to merge 1 commit into
mainfrom
agent/opencode/gate-codex-receipt

Conversation

@frankxai

@frankxai frankxai commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

independent-review-policy can never pass on this repo. The gate parses only STARLIGHT-INDEPENDENT-REVIEW-V1, while Codex posts codex-review-state:v1 + codex-review-receipt:v1 as the chatgpt-codex-connector bot. The app is in TRUSTED_APPS and is still rejected, because the attestor rule requires the author to be frankxai.

Evidence: merged PRs #625, #567, #566, #565 all show this check as FAILURE. The check is red across merges, so it is teaching bypasses rather than gating anything.

Change

  • codex_receipt(comment, head) reads the Codex payload and requires:
    • app and author are both chatgpt-codex-connector
    • comment not edited (created_at == updated_at)
    • code_review and security_review both completed at the exact head
    • no unresolved findings in either
  • evaluate() tries this before the attestor rule; a matching-but-invalid receipt fails closed.

Deliberately strict: a security review that failed on quota is not a pass. #638 stays blocked until Codex quota resets or a real receipt exists.

Verification

python -m pytest tools/merge-review/tests/test_merge_review_gate.py -q → 42 passed, 104 subtests passed.

Five new tests: clean pass, security-quota failure, wrong head, raw token without app, unresolved findings.

Scope

Gate only. No PR is merged by this change.


Proof this PR
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

The gate only parsed STARLIGHT-INDEPENDENT-REVIEW-V1. Codex posts codex-review-state:v1 plus codex-review-receipt:v1 as its own bot account, so chatgpt-codex-connector could never satisfy a check it is allowlisted for.

Adds codex_receipt(): requires the app+bot pair, created==updated, code_review and security_review both completed at the exact head with no unresolved findings. A quota failure is not a pass. Five tests cover pass, security-quota failure, wrong head, raw token, and unresolved findings.

frankxai commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

Claude review at 944b0cba (different vendor from the maker; not a pass). Verdict: request changes. Merging as-is unblocks nothing.

I ran the new codex_receipt() against the real Codex comments on this repo (captured from #636 and #653). It returns None for every one of them, so independent-review-policy stays red exactly as before:

Real comment Original #651 result
Codex receipt on #636 (codex-review-receipt:v1, reviewed 53e307d635, never edited) ignored
Codex summary on #653 (codex-review-state:v1) ignored
Codex usage-limit notice ignored

P1 findings

  1. Login mismatch. REST returns chatgpt-codex-connector[bot]; the gate compares against chatgpt-codex-connector. No real comment can match.
  2. Two comments, not one. Codex puts codex-review-state:v1 in the summary comment and codex-review-receipt:v1 in a separate comment. The gate requires both markers in one body.
  3. The summary is edited in place. The bot rewrites the summary on every review (fix(site): render OperationalProofConsole visible on SSR first paint #653: created 13:35:36Z, updated 13:37:37Z; merge-review: accept the estate reviewer's receipt for low-risk changes #647 updated a day later), so created_at == updated_at rejects it for any PR reviewed more than once. Only the receipt comment is posted fresh and never edited, so the gate has to read that one.
  4. Self-review. The Codex path never checks the maker. 45 open PRs across the six repos I sampled come from Codex branches, and Codex would count as their own reviewer. That breaks the gate's first rule.
  5. The CTO rule is bypassed. reviewer_allowed() requires a CTO PASS on high-risk paths. The Codex path skips that check, including for tools/merge-review/ itself.

P2: a stale or wrong-head Codex comment returns fail and stops the loop, which can hide a valid attestor receipt at the current head. A stale receipt is just not evidence; it should be skipped.

Why the 42 tests passed: the fixtures were written from an assumed format, not captured from GitHub. The fix below tests against the captured payloads.

Proposed fix (patch below, 48 passed, 104 subtests; the ten new tests use real captured comments, and the original code fails them):

  • Read only the never-edited receipt comment. Match the login with or without [bot], require user.type == Bot and the Codex App slug, bind Reviewed commit to the head by prefix, and require the no-major-issues phrase.
  • Take the maker from the head ref (agent/<harness>/…, codex/…). Codex cannot review a Codex-made change or one whose maker is unknown.
  • High-risk paths still need the CTO PASS.
  • A non-matching Codex comment is skipped, never fail-closed.

Scope stays the same: the gate only. Still needed besides this patch: Codex code-review quota (reviews on #636 hit the usage limit), and a CTO PASS on this PR itself, since it touches tools/merge-review/.

Patch (gate + tests). Includes tests/codex_captured.json, three captured Codex comments.
--- tools.orig/merge-review/merge_review_gate.py	2026-12-01 01:57:23.020041071 +0100
+++ tools/merge-review/merge_review_gate.py	2026-12-01 01:58:01.760601965 +0100
@@ -13,12 +13,16 @@
 # A receipt counts only if GitHub records it as posted through an allowlisted App.
 # A null performed_via_github_app means a raw token (PAT or gh CLI) and is rejected.
 TRUSTED_APPS = {'cursor', 'chatgpt-codex-connector'}
-# Codex posts its review as its own bot account, not as an attestor, so the
-# attestor rule is replaced by a strict app+login pair for this receipt format.
-CODEX_BOT = 'chatgpt-codex-connector'
-CODEX_STATE_RE = re.compile(r'<!--\s*codex-review-state:v1\s*(\{.*?\})\s*-->', re.S)
+# Codex posts its review as its own bot account, not as an attestor. REST reports
+# the login with a [bot] suffix; the App slug has none.
+CODEX_APP = 'chatgpt-codex-connector'
+CODEX_LOGINS = {'chatgpt-codex-connector[bot]', 'chatgpt-codex-connector'}
+# Codex posts a fresh, never-edited receipt comment per completed code review. The
+# summary comment carrying codex-review-state:v1 is edited in place by the bot on
+# every new review, so it cannot meet the never-edited rule and is not read.
 CODEX_RECEIPT_MARKER = '<!-- codex-review-receipt:v1 -->'
-CODEX_REVIEWS = ('code_review', 'security_review')
+CODEX_REVIEWED_RE = re.compile(r'\*\*Reviewed commit:\*\*\s*`([0-9a-f]{10,40})`')
+CODEX_CLEAN_PHRASE = "Didn't find any major issues"
 # Seats, models or bots that may author a change. The reviewer must be a different one.
 # dependabot and github-actions are bot makers: they are never reviewers, so their
 # high-risk changes (manifests, lockfiles, workflows) still need a CTO PASS.
@@ -132,39 +136,39 @@
 MAX_EDIT_LOOKUPS = 5
 
 
-def codex_receipt(comment, head):
-    """Read a Codex review comment at this exact head.
+def codex_receipt(comment, head, maker=None, risky=False):
+    """Read a Codex code-review receipt at this exact head.
 
-    Returns (status, detail): status is 'pass', 'fail', or None when the comment
-    is not a Codex receipt. Both the code review and the security review must be
-    completed with no unresolved findings; a quota failure is not a pass.
+    Returns 'pass' or None; never 'fail', so a stale or non-matching Codex comment
+    cannot mask a valid attestor receipt further back. Codex is one review provider
+    under the existing policy: it cannot review a Codex-made change or one whose
+    maker is unknown, and it is not the CTO PASS that high-risk paths require.
     """
-    if (comment.get('user', {}).get('login') != CODEX_BOT
-            or posting_app(comment) != CODEX_BOT
+    if (maker in (None, 'codex') or risky
+            or comment.get('user', {}).get('login') not in CODEX_LOGINS
+            or comment.get('user', {}).get('type', 'Bot') != 'Bot'
+            or posting_app(comment) != CODEX_APP
             or not comment.get('created_at')
             or comment.get('created_at') != comment.get('updated_at')):
-        return None, None
+        return None
     body = comment.get('body', '')
-    if CODEX_RECEIPT_MARKER not in body or len(body) > 60000:
-        return None, None
-    match = CODEX_STATE_RE.search(body)
-    if not match:
-        return None, None
-    try:
-        state = json.loads(match.group(1))
-    except ValueError:
-        return 'fail', 'Codex review state is not valid JSON.'
-    for name in CODEX_REVIEWS:
-        review = state.get(name)
-        if not isinstance(review, dict):
-            return 'fail', f'Codex {name} is missing from the receipt.'
-        if review.get('commit_sha') != head:
-            return 'fail', f'Codex {name} is not bound to the current head.'
-        if review.get('status') != 'completed':
-            return 'fail', f'Codex {name} did not complete (status {review.get("status")}).'
-        if review.get('has_unresolved_findings'):
-            return 'fail', f'Codex {name} reports unresolved findings.'
-    return 'pass', 'Codex code and security review completed at the exact head.'
+    if (len(body) > 60000 or CODEX_RECEIPT_MARKER not in body
+            or CODEX_CLEAN_PHRASE not in body):
+        return None
+    match = CODEX_REVIEWED_RE.search(body)
+    if not match or not head.startswith(match.group(1)):
+        return None
+    return 'pass'
+
+
+def maker_from_ref(ref):
+    """Harness that made the branch, from agent/<harness>/<scope> or codex/<scope>."""
+    parts = (ref or '').split('/')
+    if len(parts) >= 3 and parts[0] == 'agent' and re.fullmatch(r'[a-z][a-z0-9-]*', parts[1]):
+        return parts[1]
+    if len(parts) >= 2 and parts[0] == 'codex':
+        return 'codex'
+    return None
 
 
 def receipt_candidate(comment, head):
@@ -216,7 +220,7 @@
     return (json.loads(run.stdout).get('data') or {}).get('node') or {}
 
 
-def evaluate(repository, number, head, files, comments, auto_merge=None):
+def evaluate(repository, number, head, files, comments, auto_merge=None, maker=None):
     if not re.fullmatch(r'[0-9a-f]{40}', head) or not files:
         return False, 'Missing or invalid source identity or changed files.'
     risky = any(item_high_risk(item) for item in files)
@@ -226,11 +230,8 @@
         return True, 'Routine plain-text notes only; required CI still applies.'
     expected_paths = {item['filename'] for item in files}
     for comment in reversed(comments):
-        codex_status, codex_detail = codex_receipt(comment, head)
-        if codex_status == 'pass':
-            return True, f'{codex_detail} Comment {comment["id"]}.'
-        if codex_status == 'fail':
-            return False, codex_detail
+        if codex_receipt(comment, head, maker, risky) == 'pass':
+            return True, f'Codex code review found no major issues at {head} in comment {comment["id"]}.'
         if (comment.get('user', {}).get('login') not in TRUSTED_ATTESTORS
                 or comment.get('author_association') not in {'OWNER', 'MEMBER', 'COLLABORATOR'}
                 or posting_app(comment) not in TRUSTED_APPS
@@ -321,7 +322,8 @@
                         item['mode'] = modes.get(item['filename'])
         comments = api(f'repos/{repository}/issues/{number}/comments?per_page=100', paginate=True)
         annotate_edit_history(comments, head)
-        ok, summary = evaluate(repository, number, head, files, comments, pr.get('auto_merge'))
+        ok, summary = evaluate(repository, number, head, files, comments, pr.get('auto_merge'),
+                               maker_from_ref(pr['head'].get('ref')))
         if api(endpoint)['head']['sha'] != head:
             ok, summary = False, 'PR head changed during evaluation; rerun for the new head.'
     except Exception as error:
--- /dev/fd/63	2026-12-01 01:58:08.998680354 +0100
+++ tools/merge-review/tests/test_merge_review_gate.py	2026-12-01 01:58:01.774676335 +0100
@@ -344,54 +344,67 @@
         gate.annotate_edit_history(comments, HEAD, lookup)
         self.assertEqual(len(calls), gate.MAX_EDIT_LOOKUPS)
         self.assertFalse(self.evaluate(comments))
-CODEX_BODY_OK = {
-    'code_review': {'commit_sha': HEAD, 'status': 'completed',
-                    'has_any_findings': False, 'has_unresolved_findings': False},
-    'security_review': {'commit_sha': HEAD, 'status': 'completed',
-                        'has_any_findings': False, 'has_unresolved_findings': False},
-}
-
-
-def codex_comment(state=None, head=HEAD, app='chatgpt-codex-connector'):
-    payload = json.dumps(state or CODEX_BODY_OK)
-    body = ('<!-- codex-pull-request-review-summary -->\n'
-            f'<!-- codex-review-state:v1 {payload} -->\n\n'
-            'Codex Review: no blocking issues.\n\n'
-            '<!-- codex-review-receipt:v1 -->\n\n'
-            f'**Reviewed commit:** `{head[:10]}`')
-    return {'id': 900, 'user': {'login': 'chatgpt-codex-connector'},
-            'author_association': 'NONE',
-            'performed_via_github_app': {'slug': app} if app else None,
-            'created_at': '2026-11-29T04:55:00Z', 'updated_at': '2026-11-29T04:55:00Z',
-            'body': body}
+
+CAPTURED = json.loads((Path(__file__).parent / 'codex_captured.json').read_text(encoding='utf8'))
+# Real comments from Starlight-Intelligence-System. The receipt reviewed 53e307d635.
+CODEX_HEAD = '53e307d6352e32b9161d14fde3fc7bd1152118a9'
+
+
+def captured(kind, **changes):
+    comment = json.loads(json.dumps(CAPTURED[kind]))
+    comment.update(changes)
+    return comment
 
 
 class CodexReceiptTests(unittest.TestCase):
-    def evaluate(self, comments):
-        return gate.evaluate('frankxai/starlight-agent-config', 110, HEAD, FILES, comments)[0]
+    def evaluate(self, comments, head=CODEX_HEAD, files=FILES, maker='antigravity'):
+        return gate.evaluate('Starlight-Intelligence/Starlight-Intelligence-System', 636,
+                             head, files, comments, maker=maker)[0]
+
+    def test_real_receipt_at_exact_head_passes(self):
+        self.assertTrue(self.evaluate([captured('receipt')]))
+
+    def test_real_receipt_for_another_head_does_not_pass(self):
+        self.assertFalse(self.evaluate([captured('receipt')], head='c' * 40))
+
+    def test_edited_receipt_does_not_pass(self):
+        self.assertFalse(self.evaluate([captured('receipt', updated_at='2026-11-29T05:10:00Z')]))
+
+    def test_receipt_without_codex_app_does_not_pass(self):
+        self.assertFalse(self.evaluate([captured('receipt', performed_via_github_app=None)]))
+
+    def test_receipt_text_posted_by_owner_token_does_not_pass(self):
+        forged = captured('receipt', user={'login': 'frankxai', 'type': 'User'})
+        self.assertFalse(self.evaluate([forged]))
+
+    def test_codex_cannot_review_codex_made_change(self):
+        self.assertFalse(self.evaluate([captured('receipt')], maker='codex'))
+
+    def test_unknown_maker_does_not_pass(self):
+        self.assertFalse(self.evaluate([captured('receipt')], maker=None))
+
+    def test_high_risk_path_still_needs_cto(self):
+        files = [{'filename': 'tools/merge-review/merge_review_gate.py', 'status': 'modified'}]
+        self.assertFalse(self.evaluate([captured('receipt')], files=files))
+
+    def test_edited_summary_and_quota_notice_do_not_pass(self):
+        self.assertFalse(self.evaluate([captured('summary'), captured('quota')]))
+
+    def test_stale_codex_receipt_does_not_mask_attestor_receipt(self):
+        attestor = receipt(headSha=CODEX_HEAD, maker='codex', provider='antigravity', pr=636,
+                           repository='Starlight-Intelligence/Starlight-Intelligence-System')
+        stale = captured('receipt', body=CAPTURED['receipt']['body'].replace('53e307d635', 'ffffffffff'))
+        self.assertTrue(self.evaluate([attestor, stale], maker='codex'))
 
-    def test_clean_codex_receipt_passes(self):
-        self.assertTrue(self.evaluate([codex_comment()]))
 
-    def test_security_quota_failure_does_not_pass(self):
-        state = json.loads(json.dumps(CODEX_BODY_OK))
-        state['security_review'] = {'commit_sha': HEAD, 'status': 'failed',
-                                    'has_any_findings': True, 'has_unresolved_findings': True}
-        self.assertFalse(self.evaluate([codex_comment(state)]))
-
-    def test_wrong_head_does_not_pass(self):
-        state = json.loads(json.dumps(CODEX_BODY_OK))
-        state['code_review']['commit_sha'] = 'c' * 40
-        self.assertFalse(self.evaluate([codex_comment(state)]))
-
-    def test_raw_token_without_app_does_not_pass(self):
-        self.assertFalse(self.evaluate([codex_comment(app=None)]))
-
-    def test_unresolved_finding_does_not_pass(self):
-        state = json.loads(json.dumps(CODEX_BODY_OK))
-        state['code_review']['has_unresolved_findings'] = True
-        self.assertFalse(self.evaluate([codex_comment(state)]))
+class MakerFromRefTests(unittest.TestCase):
+    def test_refs(self):
+        self.assertEqual(gate.maker_from_ref('agent/opencode/gate-codex-receipt'), 'opencode')
+        self.assertEqual(gate.maker_from_ref('codex/fix-thing'), 'codex')
+        self.assertEqual(gate.maker_from_ref('agent/codex/x'), 'codex')
+        self.assertIsNone(gate.maker_from_ref('feature/x'))
+        self.assertIsNone(gate.maker_from_ref(None))
 
 
 if __name__ == '__main__':
-    unittest.main()
+    unittest.main()
--- /dev/null
+++ b/tools/merge-review/tests/codex_captured.json
@@ -0,0 +1,44 @@
+{
+ "summary": {
+  "id": 7280067763,
+  "body": "<!-- codex-pull-request-review-summary -->\n<!-- codex-review-state:v1 {\"code_review\":{\"commit_sha\":\"19a5a5dde5c8accebfa55b25c70b03ccc34320cf\",\"has_any_findings\":false,\"has_unresolved_findings\":false,\"status\":\"completed\"},\"security_review\":{\"commit_sha\":\"19a5a5dde5c8accebfa55b25c70b03ccc34320cf\",\"has_any_findings\":null,\"has_unresolved_findings\":null,\"status\":\"completed\"}} -->\n<!-- codex-security-review:v1 {\"blockingSeverityThreshold\":\"P0\",\"headSha\":\"19a5a5dde5c8accebfa55b25c70b03ccc34320cf\",\"mergeGateEnabled\":false,\"pullRequestNumber\":653,\"repository\":\"Starlight-Intelligence/Starlight-Intelligence-System\",\"status\":\"completed\"} -->\n<details>\n<summary><strong>Codex Review Summary</strong>: \u2705 Completed</summary>\n\nThis comment shows the latest Codex review activity on this pull request.\n\n| Review | Status | Commit | Review trigger |\n| --- | --- | --- | --- |\n| \ud83d\udcdd **Code Review** | \u2705 **Completed** <relative-time datetime=\"2026-11-30T13:36:52.147131Z\">2026-11-30T13:36:52.147131Z</relative-time> | `19a5a5d` | PR opened |\n| \ud83d\udd12 **Security Review** | \u2705 **Completed** <relative-time datetime=\"2026-11-30T13:37:36.288299Z\">2026-11-30T13:37:36.288299Z</relative-time> | `19a5a5d` | PR opened |\n\n\n\n<details> <summary>\u2139\ufe0f About Codex in GitHub</summary>\n<br/>\n\n[Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you\n- Open a pull request for review\n- Mark a draft as ready\n- Comment \"@codex review\" or \"@codex security review\".\n\nCodex reacts with \ud83d\udc40 while any review is running, comments if it has suggestions, and reacts with \ud83d\udc4d once all reviews finish with no findings.\n\n</details>\n\n</details>",
+  "created_at": "2026-11-30T13:35:36Z",
+  "updated_at": "2026-11-30T13:37:37Z",
+  "author_association": "NONE",
+  "user": {
+   "login": "chatgpt-codex-connector[bot]",
+   "type": "Bot"
+  },
+  "performed_via_github_app": {
+   "slug": "chatgpt-codex-connector"
+  }
+ },
+ "receipt": {
+  "id": 7250943061,
+  "body": "<!-- codex-review-receipt:v1 -->\n\nCodex Review: Didn't find any major issues. Already looking forward to the next diff.\n\n**Reviewed commit:** `53e307d635`\n\n<details> <summary>\u2139\ufe0f About Codex in GitHub</summary>\n<br/>\n\n[Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you\n- Open a pull request for review\n- Mark a draft as ready\n- Comment \"@codex review\".\n\nIf Codex has suggestions, it will comment; otherwise it will react with \ud83d\udc4d.\n\n\n\n\nCodex can also answer questions or update the PR. Try commenting \"@codex address that feedback\".\n            \n</details>",
+  "created_at": "2026-11-29T04:55:35Z",
+  "updated_at": "2026-11-29T04:55:35Z",
+  "author_association": "NONE",
+  "user": {
+   "login": "chatgpt-codex-connector[bot]",
+   "type": "Bot"
+  },
+  "performed_via_github_app": {
+   "slug": "chatgpt-codex-connector"
+  }
+ },
+ "quota": {
+  "id": 7221401517,
+  "body": "You have reached your Codex usage limits for code reviews. You can see your limits in the [Codex usage dashboard](https://chatgpt.com/codex/cloud/settings/usage).\nTo continue using code reviews, add credits to your account and enable them for code reviews in your [settings](https://chatgpt.com/settings/code-review).",
+  "created_at": "2026-11-27T14:55:27Z",
+  "updated_at": "2026-11-27T14:55:27Z",
+  "author_association": "NONE",
+  "user": {
+   "login": "chatgpt-codex-connector[bot]",
+   "type": "Bot"
+  },
+  "performed_via_github_app": {
+   "slug": "chatgpt-codex-connector"
+  }
+ }
+}
\ No newline at end of file

Generated by Claude Code

@chatgpt-codex-connector

Copy link
Copy Markdown

Summary

Testing

  • ✅ python -m pytest tools/merge-review/tests/test_merge_review_gate.py -q — 48 passed, 104 subtests passed.
  • ✅ python -m json.tool tools/merge-review/tests/codex_captured.json
  • ✅ git diff --check
  • ✅ git status --short --branch — clean working tree on agent/codex/fix-real-codex-receipts.

View task →

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants