Skip to content

feat(post): deliver current-head replies idempotently - #832

Merged
EffortlessSteven merged 9 commits into
mainfrom
codex/issue828-replies-fallback
Aug 5, 2026
Merged

EffortlessSteven merged 9 commits into
mainfrom
codex/issue828-replies-fallback

Conversation

@EffortlessSteven

@EffortlessSteven EffortlessSteven commented Aug 5, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Implements M1c: deliver replies idempotently and preserve fallback until GitHub confirms delivery #828 reply delivery, current-head retry reuse, and conservative body fallback on top of M1b: execute the pending-review delivery lifecycle and cleanup transaction #827.
  • Validates planned replies against the exact current-head source thread, path, line, side, claim identity, and body digest before posting.
  • Reuses only confirmed current-head inline/reply delivery; stale, missing, malformed, partial, or unconfirmed delivery remains eligible for fallback.
  • Persists reply receipts and retry decisions; transport failures remain delivery failures and do not fabricate code findings.
  • Preserves rendered GitHub comment bodies in pending-review payloads, including unsafe-review suggestion blocks.
  • Paginates existing review comments, validates returned reply parent identity, and removes confirmed multiline body surfaces deterministically.

Non-goals: pending-review transport from #827 is unchanged in responsibility; this PR does not implement proof execution, replanning, public-item ranking/compaction, release work, or policy-threshold changes.

Policy receipts

Verification

  • cargo fmt --all -- --check — pass.
  • Focused reply/retry/fallback tests — pass; 26 delivery tests.
  • Focused CLI suggestion-payload regression test — pass.
  • cargo test --locked --bin ub-review -- --test-threads=4 — 764 passed.
  • cargo clippy --workspace --all-targets --locked -- -D warnings — pass.
  • cargo doc --workspace --no-deps --locked — pass.
  • cargo xtask policy-check — pass; existing overdue suppression-ledger review warning remains.
  • python scripts/verify-bun-review-artifacts.py --self-test — pass.
  • git diff --check — pass.
  • Full-context ripr check --mode ready — 0 unsuppressed exposure gaps; local output notes Python preview unavailable, so hosted execution remains authoritative.
  • cargo test --workspace --all-targets --locked — unverified: timed out after 364 seconds with no diagnostics on the final local attempt; the prior hosted run’s full workspace test failure was the fixed tuple-mapping regression, which passes locally now.

The tests prove exact current-head identity, paginated comment collection, reply source binding including the returned parent, no duplicate on retry, wrong-head rejection, receipt persistence, rendered multiline comment-body preservation, and confirmed-versus-unconfirmed body behavior. They do not prove GitHub production behavior beyond the fake transport/API contract; the hosted exact-head gate supplies repository integration proof.

CI budget

  • Planned band: elevated
  • Reason: GitHub delivery transaction and strict-zero RIPR proof require the repository gate and full artifact packet.

Agent notes

@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Summary by CodeRabbit

  • New Features

    • Added support for delivering review feedback as direct replies alongside inline comments.
    • Replies preserve source-thread context and avoid duplicate or already-confirmed deliveries.
    • Review updates can retry safely using delivery confirmations and status checks.
  • Bug Fixes

    • Improved handling of partial deliveries, retries, cleanup, and previously submitted review content.
    • Prevented reply-required feedback from being incorrectly suppressed as a duplicate.
  • Quality Improvements

    • Added safeguards for delivery targets, review versions, comment identities, and reply records.

Walkthrough

The PR adds direct GitHub reply delivery alongside inline comments. It validates current heads and source threads, reuses receipts to prevent duplicate posts, filters confirmed content, records retry decisions, validates artifacts, and adds tests.

Changes

Reply delivery flow

Layer / File(s) Summary
Delivery planning and contracts
src/delivery_transaction.rs, src/github_delivery.rs, src/review_topics.rs
Planning supports inline and reply actions. Reply deliveries require a current source thread. PlannedDelivery exposes action, source thread, and claim metadata.
Inline and reply execution
src/github_delivery.rs
Execution retrieves comments, skips confirmed deliveries, posts replies, validates identities, records receipts and retry decisions, and submits only remaining inline content.
Artifact validation and behavioral coverage
scripts/verify-bun-review-artifacts.py, src/github_delivery.rs, .ripr/suppressions.toml
Artifact validation checks reply receipts, retry decisions, and secret markers. Tests cover duplicate prevention, stale sources, response identities, receipts, body filtering, pagination, and retry output. Suppressions document probe coverage.

Estimated code review effort: 5 (Critical) | ~90 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ReviewTopics
  participant DeliveryTransaction
  participant GitHubDelivery
  participant GitHubAPI
  participant ArtifactValidator
  ReviewTopics->>DeliveryTransaction: provide inline and reply delivery plans
  DeliveryTransaction->>GitHubDelivery: execute delivery transaction
  GitHubDelivery->>GitHubAPI: retrieve comments and post replies
  GitHubAPI-->>GitHubDelivery: return delivery identities
  GitHubDelivery->>ArtifactValidator: persist receipts and retry decisions
  ArtifactValidator-->>DeliveryTransaction: validate delivery artifacts
Loading

Possibly related issues

Possibly related PRs

Suggested labels: enhancement, codex

Poem

A rabbit checks the current head,
Then posts replies where threads are led.
Receipts prevent a second run,
Retry records show what was done.
Confirmed inline text is cleared—
Each delivery path is steered.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main change: idempotent delivery of current-head replies.
Description check ✅ Passed The description covers all template sections and clearly documents scope, receipts, verification results, CI budget, and the unverified workspace timeout.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/issue828-replies-fallback

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot added codex enhancement New feature or request labels Aug 5, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: de54dc985b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/github_delivery.rs
Comment on lines +747 to +760
let output = transport.send_json(
"POST",
&format!(
"{}/repos/{}/pulls/{}/comments",
context.api, context.repo, context.pull_number
),
context.token,
&payload_path,
&[
"Accept: application/vnd.github+json",
"Content-Type: application/json",
"X-GitHub-Api-Version: 2022-11-28",
],
)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Revalidate the PR head before posting public replies

When the PR head changes after the initial head fetch/comment listing but before this POST, the reply is published immediately against the old source comment; the later ensure_heads_match in both callers can only report failure after the public reply exists, and the cleanup path only deletes pending reviews, not direct replies. Recheck the head immediately before each public reply POST, or otherwise make the reply cleanup-able, to preserve the exact-current-head guarantee under this race.

Useful? React with 👍 / 👎.

Comment thread src/github_delivery.rs
Comment on lines +720 to +728
id.as_deref() == Some(source_thread_id)
&& comment.get("commit_id").and_then(serde_json::Value::as_str)
== Some(context.exact_head_sha)
&& comment.get("path").and_then(serde_json::Value::as_str)
== Some(planned.location().0)
&& comment.get("line").and_then(serde_json::Value::as_u64)
== Some(u64::from(planned.location().1))
&& comment.get("side").and_then(serde_json::Value::as_str)
== Some(planned.location().2)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Choose only top-level comments as reply sources

This source lookup accepts any current review comment with the same id/path/line/side, including comments that are themselves replies (in_reply_to_id is set). In a thread that already has replies, the planned source id can therefore point at a reply, and GitHub rejects replies-to-replies instead of delivering the follow-up; require the selected source to be top-level or resolve the top-level parent before posting.

Useful? React with 👍 / 👎.

Comment thread src/github_delivery.rs
Comment on lines +223 to +228
let response = replies
.last()
.map(|receipt| serde_json::json!({"id": receipt.comment_id, "state": "commented"}))
.unwrap_or_else(|| serde_json::json!({"state": "already_delivered"}));
return Ok(PendingReviewPostOutcome {
response,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the review body in reply-only deliveries

When all remaining comment surfaces are replies, this early return skips pending-review submission entirely, so api_payload.body is never posted or filtered through body_after_confirmed_delivery. A review that contains reply comments plus summary-only findings or other non-duplicate body text will silently publish only the replies and drop the rest of the compiler's public review content; submit any non-empty filtered body separately before returning.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.ripr/suppressions.toml:
- Around line 16375-16380: Remove any consecutive duplicate [[suppressions]]
headers in .ripr/suppressions.toml, including the repeated entries beginning
near the suppression identified by finding_id
"probe:src_github_delivery.rs:field_construction:8392a8d6". Ensure each
suppression record has one header and retains its kind, finding_id, owner, and
reason fields, with no empty array entries.
- Around line 16376-16379: Replace the blanket suppression rationale in the
repeated exposure_gap entries with narrowly scoped suppressions only after
reviewing the field_construction, return_value, and error_path probes against
the uncovered paths in src/github_delivery.rs: pending-review payload tuple
mapping, in_reply_to_id validation in execute_reply_deliveries, and multiline
filtering in body_after_confirmed_delivery. Ensure each retained suppression is
backed by a test that asserts the specific behavior, and remove entries not
pinned by tests; avoid relying on positional suffixed finding IDs that may shift
after refactoring.

In `@scripts/verify-bun-review-artifacts.py`:
- Around line 8567-8626: Split require_reply_delivery_artifacts into two
helpers: one validating delivery-reply-receipts.json, including receipt schema,
fields, duplicate identities, and comment IDs; and another validating
delivery-retry-decisions.json, including array shape, decision status, and
identity. Keep the top-level function responsible for path detection, early
return, loading or delegating each existing artifact block, and preserve all
current validation behavior and failure messages.
- Line 8444: Update require_reply_delivery_artifacts to accept an optional
transaction head and validate the reply receipt’s exact_head_sha against it when
available. Reorder the caller so head_sha is read before invoking the function,
while preserving existing artifact checks when no transaction head is present.

In `@src/github_delivery.rs`:
- Around line 825-851: The line-based filtering in body_after_confirmed_delivery
incorrectly matches whole comment text, so multi-line suggestions are retained
and shorter bodies can over-match. Change the filtering to use each confirmed
PlannedDelivery’s stable claim_id marker emitted by the body generator, while
preserving unrelated lines, and add coverage for a confirmed comment containing
a suggestion.
- Around line 316-330: Update execute_reply_deliveries to return each delivery
receipt together with its matched planned item, preserving the full delivery
identity used elsewhere. In both the reply-only branch and the later
confirmed_for_body construction, remove the duplicated all_planned find lookups
and push the returned planned items directly, so confirmation cannot select an
ambiguous item.
- Around line 557-573: Update fetch_pull_review_comments to retrieve every
review-comment page instead of limiting results to the first 100 comments.
Follow the API’s pagination mechanism until the final page, validate that each
response is an array, and combine all comment arrays into the single array
returned to execute_reply_deliveries and prior_confirmed_deliveries.
- Around line 508-525: Import the anyhow bail macro in the module containing the
action match, alongside the existing anyhow::ensure import, so the
unsupported-action branch in the delivery plan parsing logic compiles;
alternatively qualify that invocation as anyhow::bail!.
- Around line 588-603: Update the receipt-loading loop around
serde_json::from_slice so parse errors for delivery-reconciliation.json or
delivery-reply-receipts.json are ignored and that file is skipped rather than
propagated. Keep read failures unchanged, and ensure receipts from valid files
still extend receipts so deliveries absent from malformed files remain
unconfirmed and follow the normal delivery path.
- Around line 761-776: Validate the reply response’s in_reply_to_id alongside
the existing commit_id and body checks in the review-comment delivery flow
before writing the receipt, requiring it to equal the planned source thread ID.
Add coverage in reply_delivery_rejects_wrong_response_identity_without_receipt
or a nearby test for a mismatched parent and assert that no receipt is written.
- Around line 236-250: Fix the pending_comments map in the pending-review
construction so it collects the payload comment (the first tuple element) rather
than the planned delivery; then strengthen
production_delivery_reconciles_head_comments_and_submission with an assertion
that requests[1].1 contains the exact pending comment body text.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: c2085f64-14e8-4053-88eb-2ee8c156c847

📥 Commits

Reviewing files that changed from the base of the PR and between 55221c1 and de54dc9.

📒 Files selected for processing (5)
  • .ripr/suppressions.toml
  • scripts/verify-bun-review-artifacts.py
  • src/delivery_transaction.rs
  • src/github_delivery.rs
  • src/review_topics.rs

Comment thread .ripr/suppressions.toml
Comment on lines +16375 to +16380
[[suppressions]]
kind = "exposure_gap"
finding_id = "probe:src_github_delivery.rs:field_construction:8392a8d6"
owner = "ub-review/core"
reason = "Exact diff-form RIPR receipt for #828: production-path fake transport tests cover current-head reply delivery, exact source binding, retry reuse, wrong-head rejection, receipt identity, and confirmed-versus-unconfirmed fallback; adapter IO/control probes are analyzer false positives against those semantic oracles. Re-verify after edits to src/github_delivery.rs or its delivery fixtures."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

Check for a duplicated [[suppressions]] header on every added entry.

The annotated file shows two consecutive [[suppressions]] lines for each added entry, starting here and repeating through line 17365. If the file contains that duplicate, TOML parses the first header as an empty table in the array. The suppression list then holds one empty entry per real entry, with no kind and no finding_id.

#!/bin/bash
# Description: Detect consecutive duplicate array-of-tables headers and count entries against required keys.
set -euo pipefail

awk '/^\[\[suppressions\]\]$/{if(prev==NR-1) print "duplicate header at line " NR; prev=NR}' .ripr/suppressions.toml

echo "--- counts ---"
grep -c '^\[\[suppressions\]\]$' .ripr/suppressions.toml
grep -c '^finding_id = ' .ripr/suppressions.toml

python - <<'PY'
import tomllib, pathlib
data = tomllib.loads(pathlib.Path(".ripr/suppressions.toml").read_text())
items = data.get("suppressions", [])
empty = [i for i, item in enumerate(items) if not item]
missing = [i for i, item in enumerate(items) if item and "finding_id" not in item]
print("entries:", len(items), "empty:", len(empty), "missing finding_id:", len(missing))
print("first empty indexes:", empty[:10])
PY
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.ripr/suppressions.toml around lines 16375 - 16380, Remove any consecutive
duplicate [[suppressions]] headers in .ripr/suppressions.toml, including the
repeated entries beginning near the suppression identified by finding_id
"probe:src_github_delivery.rs:field_construction:8392a8d6". Ensure each
suppression record has one header and retains its kind, finding_id, owner, and
reason fields, with no empty array entries.

Comment thread .ripr/suppressions.toml Resolved
Comment thread scripts/verify-bun-review-artifacts.py Resolved
Comment on lines +8567 to +8626
def require_reply_delivery_artifacts(root: pathlib.Path) -> None:
"""Validate direct current-head reply receipts produced by #828."""
receipts_path = root / "review/delivery-reply-receipts.json"
decisions_path = root / "review/delivery-retry-decisions.json"
if not receipts_path.exists() and not decisions_path.exists():
return
if receipts_path.exists():
receipts = load_json(receipts_path)
if not isinstance(receipts, list):
fail("delivery-reply-receipts.json must be an array")
identities = set()
comment_ids = set()
for index, receipt in enumerate(receipts):
if not isinstance(receipt, dict):
fail(f"reply delivery receipt {index} is not an object")
if receipt.get("schema") != "ub-review.reply_delivery_receipt.v1":
fail(f"reply delivery receipt {index} has the wrong schema")
if receipt.get("action") != "reply":
fail(f"reply delivery receipt {index} action is not reply")
head = receipt.get("exact_head_sha")
if not isinstance(head, str) or not head:
fail(f"reply delivery receipt {index} exact head is missing")
if receipt.get("confirmed_head_sha") != head:
fail(f"reply delivery receipt {index} confirmation head is wrong")
thread = receipt.get("source_thread_id")
if not isinstance(thread, str) or not thread:
fail(f"reply delivery receipt {index} source thread is missing")
comment_id = receipt.get("comment_id")
if not isinstance(comment_id, str) or not comment_id:
fail(f"reply delivery receipt {index} comment id is missing")
if comment_id in comment_ids:
fail("reply delivery receipts contain duplicate comment ids")
comment_ids.add(comment_id)
identity = tuple(
receipt.get(field)
for field in (
"exact_head_sha",
"claim_id",
"action",
"path",
"line",
"side",
"source_thread_id",
"expected_body_digest",
)
)
if identity in identities:
fail("reply delivery receipts contain duplicate identities")
identities.add(identity)
if decisions_path.exists():
decisions = load_json(decisions_path)
if not isinstance(decisions, list):
fail("delivery-retry-decisions.json must be an array")
for index, decision in enumerate(decisions):
if not isinstance(decision, dict):
fail(f"delivery retry decision {index} is not an object")
if decision.get("status") not in {"confirmed_current_head", "unconfirmed"}:
fail(f"delivery retry decision {index} has an invalid status")
if not isinstance(decision.get("identity"), dict):
fail(f"delivery retry decision {index} identity is missing")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Split the function to clear Ruff PLR0912.

Ruff reports 19 branches against a limit of 12. The function already contains two independent blocks guarded by receipts_path.exists() and decisions_path.exists(). Extract each block into its own helper. The branch count then falls under the limit and each helper validates one artifact.

♻️ Proposed refactor
 def require_reply_delivery_artifacts(root: pathlib.Path) -> None:
     """Validate direct current-head reply receipts produced by `#828`."""
     receipts_path = root / "review/delivery-reply-receipts.json"
     decisions_path = root / "review/delivery-retry-decisions.json"
     if not receipts_path.exists() and not decisions_path.exists():
         return
     if receipts_path.exists():
-        receipts = load_json(receipts_path)
-        ...
+        _require_reply_receipts(receipts_path)
     if decisions_path.exists():
-        decisions = load_json(decisions_path)
-        ...
+        _require_retry_decisions(decisions_path)
🧰 Tools
🪛 Ruff (0.16.1)

[warning] 8567-8567: Too many branches (19 > 12)

(PLR0912)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/verify-bun-review-artifacts.py` around lines 8567 - 8626, Split
require_reply_delivery_artifacts into two helpers: one validating
delivery-reply-receipts.json, including receipt schema, fields, duplicate
identities, and comment IDs; and another validating
delivery-retry-decisions.json, including array shape, decision status, and
identity. Keep the top-level function responsible for path detection, early
return, loading or delegating each existing artifact block, and preserve all
current validation behavior and failure messages.

Source: Linters/SAST tools

Comment thread src/github_delivery.rs Resolved
Comment thread src/github_delivery.rs
Comment on lines +508 to +525
let action = topic
.get("planned_action")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| anyhow::anyhow!("delivery plan has no action"))?;
let (action, source_thread_id) = match action {
"inline" => (DeliveryAction::Inline, None),
"reply" => {
let thread_id = topic
.get("planned_thread_id")
.and_then(serde_json::Value::as_str)
.filter(|value| !value.trim().is_empty())
.ok_or_else(|| {
anyhow::anyhow!("reply delivery plan has no current source thread")
})?;
(DeliveryAction::Reply, Some(thread_id.to_owned()))
}
other => bail!("unsupported delivery action {other:?}"),
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check the anyhow imports in src/github_delivery.rs and how bail/ensure are referenced.
set -euo pipefail

sed -n '1,32p' src/github_delivery.rs
rg -n -e '\buse anyhow' -e '\bbail!' -e '\bensure!' src/github_delivery.rs | head -40

Repository: EffortlessMetrics/ub-review

Length of output: 3109


Import anyhow::bail before using it.

src/github_delivery.rs imports use anyhow::ensure, but line 524 calls bail!; this does not bring that macro into scope and can block compilation. Add use anyhow::bail; or call anyhow::bail! directly.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/github_delivery.rs` around lines 508 - 525, Import the anyhow bail macro
in the module containing the action match, alongside the existing anyhow::ensure
import, so the unsupported-action branch in the delivery plan parsing logic
compiles; alternatively qualify that invocation as anyhow::bail!.

Comment thread src/github_delivery.rs Resolved
Comment thread src/github_delivery.rs
Comment on lines +588 to +603
for path in [
args.out.join("delivery-reconciliation.json"),
args.out.join("delivery-reply-receipts.json"),
] {
if !path.exists() {
continue;
}
let value: serde_json::Value = serde_json::from_slice(
&fs::read(&path).with_context(|| format!("read {}", path.display()))?,
)?;
if let Some(array) = value.as_array() {
receipts.extend(array.iter().cloned());
} else if let Some(array) = value.get("receipts").and_then(serde_json::Value::as_array) {
receipts.extend(array.iter().cloned());
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Treat an unparsable receipt file as unconfirmed instead of failing the delivery.

serde_json::from_slice propagates its error, so a truncated or corrupted delivery-reconciliation.json or delivery-reply-receipts.json aborts the whole run before any comment is posted. A killed prior run can leave exactly that state, and the run that should recover it fails instead.

The PR objectives state that malformed deliveries remain eligible for fallback. Skip a receipt file that does not parse, and leave the affected deliveries unconfirmed so the normal delivery path runs.

🛡️ Proposed fix
-        let value: serde_json::Value = serde_json::from_slice(
-            &fs::read(&path).with_context(|| format!("read {}", path.display()))?,
-        )?;
+        let bytes = fs::read(&path).with_context(|| format!("read {}", path.display()))?;
+        let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
+            // A malformed prior receipt proves nothing. Leave the planned
+            // deliveries unconfirmed so the delivery path re-runs.
+            continue;
+        };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for path in [
args.out.join("delivery-reconciliation.json"),
args.out.join("delivery-reply-receipts.json"),
] {
if !path.exists() {
continue;
}
let value: serde_json::Value = serde_json::from_slice(
&fs::read(&path).with_context(|| format!("read {}", path.display()))?,
)?;
if let Some(array) = value.as_array() {
receipts.extend(array.iter().cloned());
} else if let Some(array) = value.get("receipts").and_then(serde_json::Value::as_array) {
receipts.extend(array.iter().cloned());
}
}
for path in [
args.out.join("delivery-reconciliation.json"),
args.out.join("delivery-reply-receipts.json"),
] {
if !path.exists() {
continue;
}
let bytes = fs::read(&path).with_context(|| format!("read {}", path.display()))?;
let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
// A malformed prior receipt proves nothing. Leave the planned
// deliveries unconfirmed so the delivery path re-runs.
continue;
};
if let Some(array) = value.as_array() {
receipts.extend(array.iter().cloned());
} else if let Some(array) = value.get("receipts").and_then(serde_json::Value::as_array) {
receipts.extend(array.iter().cloned());
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/github_delivery.rs` around lines 588 - 603, Update the receipt-loading
loop around serde_json::from_slice so parse errors for
delivery-reconciliation.json or delivery-reply-receipts.json are ignored and
that file is skipped rather than propagated. Keep read failures unchanged, and
ensure receipts from valid files still extend receipts so deliveries absent from
malformed files remain unconfirmed and follow the normal delivery path.

Comment thread src/github_delivery.rs Resolved
Comment thread src/github_delivery.rs Resolved
@codecov

codecov Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.87629% with 40 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/github_delivery.rs 95.83% 40 Missing ⚠️

📢 Thoughts on this report? Let us know!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
.ripr/suppressions.toml (1)

16377-17607: 📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

Narrow the reused blanket reason across the new GitHub-delivery suppressions.

Nearly every new exposure_gap entry in this range (call_deletion, error_path, field_construction, match_arm, predicate, and return_value probes on src_github_delivery.rs, spanning hundreds of distinct finding_id values) repeats the same sentence: "current-head reply source validation, paginated comment retrieval, multiline fallback removal, and response identity tests cover this adapter probe." No entry names the specific test function that discriminates its specific probe.

A past review on this exact file flagged this pattern as Major for a prior block and asked to "suppress only the entries that a test actually pins" and to review field_construction, return_value, and error_path probes against uncovered paths rather than assert blanket coverage. This new block reintroduces the same pattern at a larger scale. Compare it to the entries added later in this same diff (lines 17731-17826), which name the exact behavior and test for each probe (for example, the in_reply_to_id rejection test and the pagination short-page test). Bring this block to the same standard: name the specific test function per finding_id, or split the generic sentence into probe-specific sentences that state which assertion pins which exact line/branch.

Without this, a future refactor of src/github_delivery.rs could silently drop real coverage for one of these hundreds of suppressed probes, and no reviewer could tell from the ledger alone which test to check.

Run the following script to check for literal duplicate finding_id values (not the intentionally suffixed .2/.3 variants) among the new entries, and to list the test names in src/github_delivery.rs that plausibly cover "current-head", "pagination", "in_reply_to_id", and "multiline" behavior, to help you fill in per-entry test names:

#!/bin/bash
# Description: Detect exact-duplicate finding_id values and list candidate covering tests.
set -euo pipefail

echo "--- exact duplicate finding_id values (excluding intentional .N suffixes) ---"
grep -o 'finding_id = "[^"]*"' .ripr/suppressions.toml \
  | sed -E 's/\.[0-9]+"$/"/' \
  | sort | uniq -c | awk '$1 > 1 {print}' | head -50

echo "--- candidate tests covering current-head / pagination / in_reply_to_id / multiline in github_delivery.rs ---"
rg -n 'fn .*(current_head|pagination|paginat|in_reply_to|multiline|wrong_head|fallback)' src/github_delivery.rs
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.ripr/suppressions.toml around lines 16377 - 17607, Narrow the blanket
reasons for the new src_github_delivery.rs exposure_gap suppressions by mapping
each finding_id to the specific test function and assertion covering its exact
branch or construction, especially field_construction, return_value, error_path,
match_arm, and predicate probes. Split entries or remove suppressions where no
test pins the behavior, and eliminate any unintended duplicate finding_id values
while preserving intentional .2/.3 variants; use the later per-test suppressions
and candidate tests around current-head, pagination, in_reply_to_id, and
multiline behavior as the naming standard.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@scripts/verify-bun-review-artifacts.py`:
- Around line 8665-8666: Update the reply delivery receipt validation around the
head check to distinguish an absent or invalid head from a present head that
differs from graph_head. Keep the missing-head diagnostic for the former, and
emit a mismatch-specific diagnostic for the latter so stale receipts are
reported accurately before require_identity runs.
- Around line 8871-8880: Extend the self-test around
require_reply_delivery_artifacts and require_identity with table-driven negative
cases that mutate exactly one field of reply_identity per iteration. Cover
mismatched head, invalid side, invalid digest length, inline identity with a
source thread, differing planned_thread_id, path mismatch, and anchor mismatch,
asserting each branch’s specific failure text while preserving the existing
wrong-claim case.

---

Outside diff comments:
In @.ripr/suppressions.toml:
- Around line 16377-17607: Narrow the blanket reasons for the new
src_github_delivery.rs exposure_gap suppressions by mapping each finding_id to
the specific test function and assertion covering its exact branch or
construction, especially field_construction, return_value, error_path,
match_arm, and predicate probes. Split entries or remove suppressions where no
test pins the behavior, and eliminate any unintended duplicate finding_id values
while preserving intentional .2/.3 variants; use the later per-test suppressions
and candidate tests around current-head, pagination, in_reply_to_id, and
multiline behavior as the naming standard.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 34fd6438-fb4f-47cc-b732-0cd0b8bc6451

📥 Commits

Reviewing files that changed from the base of the PR and between de54dc9 and ff9d552.

📒 Files selected for processing (3)
  • .ripr/suppressions.toml
  • scripts/verify-bun-review-artifacts.py
  • src/github_delivery.rs

Comment on lines +8665 to +8666
if not isinstance(head, str) or not head or head != graph_head:
fail(f"reply delivery receipt {index} exact head is missing")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Separate the head-mismatch diagnostic from the missing-head diagnostic.

Line 8665 now also fails when head is present but differs from graph_head. The message still reports "exact head is missing". An operator reading that message looks for an absent field instead of a stale receipt. require_identity reports the accurate reason ("is bound to another head") at line 8604, but line 8665 runs first and wins.

🐛 Proposed fix
             head = receipt.get("exact_head_sha")
-            if not isinstance(head, str) or not head or head != graph_head:
+            if not isinstance(head, str) or not head:
                 fail(f"reply delivery receipt {index} exact head is missing")
+            if head != graph_head:
+                fail(f"reply delivery receipt {index} is bound to another head")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if not isinstance(head, str) or not head or head != graph_head:
fail(f"reply delivery receipt {index} exact head is missing")
if not isinstance(head, str) or not head:
fail(f"reply delivery receipt {index} exact head is missing")
if head != graph_head:
fail(f"reply delivery receipt {index} is bound to another head")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/verify-bun-review-artifacts.py` around lines 8665 - 8666, Update the
reply delivery receipt validation around the head check to distinguish an absent
or invalid head from a present head that differs from graph_head. Keep the
missing-head diagnostic for the former, and emit a mismatch-specific diagnostic
for the latter so stale receipts are reported accurately before require_identity
runs.

Comment on lines +8871 to +8880
invalid_reply = dict(reply_identity, claim_id="wrong-claim")
write_self_test_json(
root / "review/delivery-retry-decisions.json",
[{"identity": invalid_reply, "status": "confirmed_current_head"}],
)
expect_self_test_failure(
"reply retry wrong claim",
"claim is absent from claim_graph.json",
lambda: require_reply_delivery_artifacts(root),
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extend the negative self-test cases to the other require_identity branches.

The self-test covers only the absent-claim branch. require_identity also rejects a mismatched head, an invalid side, an invalid digest length, an inline identity that carries a source thread, a reply thread that differs from planned_thread_id, a path mismatch, and an anchor mismatch. None of those branches has coverage, so a future edit can silently disable them.

Add table-driven cases that mutate one field of reply_identity per iteration and assert the matching failure text.

💚 Proposed addition
         expect_self_test_failure(
             "reply retry wrong claim",
             "claim is absent from claim_graph.json",
             lambda: require_reply_delivery_artifacts(root),
         )
+        for label, overrides, expected in (
+            ("reply retry wrong head", {"exact_head_sha": "b" * 40}, "bound to another head"),
+            ("reply retry wrong side", {"side": "MIDDLE"}, "side is invalid"),
+            ("reply retry short digest", {"expected_body_digest": "abc"}, "body digest is invalid"),
+            ("reply retry wrong thread", {"source_thread_id": "999"}, "source thread does not match"),
+            ("reply retry wrong anchor", {"line": 13}, "line does not match"),
+        ):
+            write_self_test_json(
+                root / "review/delivery-retry-decisions.json",
+                [{"identity": dict(reply_identity, **overrides), "status": "unconfirmed"}],
+            )
+            expect_self_test_failure(
+                label, expected, lambda: require_reply_delivery_artifacts(root)
+            )
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/verify-bun-review-artifacts.py` around lines 8871 - 8880, Extend the
self-test around require_reply_delivery_artifacts and require_identity with
table-driven negative cases that mutate exactly one field of reply_identity per
iteration. Cover mismatched head, invalid side, invalid digest length, inline
identity with a source thread, differing planned_thread_id, path mismatch, and
anchor mismatch, asserting each branch’s specific failure text while preserving
the existing wrong-claim case.

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

Labels

codex enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant