Skip to content

feat(review): define transactional delivery contract (#765) - #826

Merged
EffortlessSteven merged 13 commits into
mainfrom
codex/issue765a-delivery-contract
Aug 4, 2026
Merged

EffortlessSteven merged 13 commits into
mainfrom
codex/issue765a-delivery-contract

Conversation

@EffortlessSteven

@EffortlessSteven EffortlessSteven commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

What changed Adds the inert, deterministic #765A delivery transaction contract. It defines planned delivery identity, exact returned-set reconciliation, confirmed receipts, transaction states, failure stages, cleanup outcomes, review-bound reconciliation envelopes, and validated JSON round-trips. The contract now: - distinguishes transaction, receipt, and reconciliation schemas; - validates invariants on deserialization through raw serde mirrors; - binds identity to exact head, claim, action, location, thread, and body digest; - rejects missing, unexpected, duplicate, malformed, wrong-head, and non-canonical delivery sets; - keeps failure and cleanup state transitions atomic and legal. No live GitHub posting behavior changes in this slice. ## Why The later posting adapter must prove that every planned inline/reply item was actually returned by GitHub for the exact head before omitting it from summary fallback. This PR supplies that fail-closed pure contract without wiring transport. ## Verification - cargo fmt --all -- --check — pass - focused delivery contract suite — 20 passed - cargo test --locked --bin ub-review -- --test-threads=4 — 736 passed - cargo clippy --workspace --all-targets --locked -- -D warnings — pass - cargo doc --workspace --no-deps --locked — pass - cargo xtask policy-check — pass; one pre-existing overdue RIPR-ledger review warning remains unchanged - python scripts/verify-bun-review-artifacts.py --self-test — pass - git diff --check — pass - full-context local RIPR — new_unsuppressed=0, suppressed_exposure_gaps=37, zero reachable-unrevealed findings - six fake-GitHub tests — all pass when isolated serially The 42 RIPR receipts are narrow and owned. The latest five cover the exact require_error fixture-helper paths and validate_cleanup_outcome completion identified by the hosted full-context scan. They cover exact false negatives on the co-located contract matrices, plus four exact test-fixture helper paths in require_error used by the invalid-deserialization matrix: serde round-trips, action/thread validation, reconciliation ordering, lifecycle/cleanup state, identifiers, and the legal-transition matrix. No threshold was raised and no broad file/function suppression was added. The default-parallel workspace all-targets run failed six process-global fake-server tests with zero requests; the serialized workspace run timed out after five minutes without diagnostics. Those results remain recorded as failed/unverified, not reported as green. The previous hosted runs exposed real contract defects (schema collision, deserialization bypass, illegal/atomicity gaps, incomplete identity labels, unbound reconciliation review IDs, and empty cleanup reasons). Those defects are fixed here. A fresh hosted exact-head run is required before merge. ## Scope boundary This PR does not wire GitHub transport, pending-review lifecycle, replies, retries, delivery fallback, output admission, or proof execution. Those remain #765B/#765C and #766.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@EffortlessSteven, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 9 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 843bfdf7-f179-46e8-8eb0-942074daf149

📥 Commits

Reviewing files that changed from the base of the PR and between 6781e80 and 7a0c203.

📒 Files selected for processing (2)
  • .ripr/suppressions.toml
  • src/delivery_transaction.rs

Summary by CodeRabbit

  • New Features

    • Added transactional tracking for review comment deliveries, including planned and observed comments, receipts, reconciliation, and lifecycle status.
    • Added validation to confirm deliveries match the intended commit, locations, actions, and content.
    • Added failure recording and cleanup outcome tracking for delivery operations.
    • Added stable JSON contracts for transaction, receipt, and reconciliation data.
  • Tests

    • Added comprehensive coverage for validation, reconciliation, serialization, lifecycle transitions, failures, and cleanup.

Walkthrough

The PR adds a public Rust module for transactional review delivery. It defines serializable delivery contracts, validates planned and observed comments, reconciles exact deliveries into receipts, and manages transaction states, failures, and cleanup outcomes with comprehensive tests.

Changes

Transactional Review Delivery

Layer / File(s) Summary
Delivery contracts and validation
src/delivery_transaction.rs, src/main.rs, .ripr/suppressions.toml
Adds serializable delivery types, schema constants, canonical identities, validation, deserialization checks, tests, suppression records, and public module wiring.
Exact delivery reconciliation
src/delivery_transaction.rs
Reconciles planned and observed deliveries by exact identity. It rejects duplicates, missing or unexpected deliveries, invalid IDs, head mismatches, and location or digest mismatches.
Transaction lifecycle and cleanup
src/delivery_transaction.rs
Adds guarded state transitions, failure recording, cleanup completion, terminal-state protection, and tests for successful and failed cleanup paths.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PlannedDeliveries
  participant reconcile_deliveries
  participant DeliveryReconciliation
  PlannedDeliveries->>reconcile_deliveries: planned deliveries and exact head
  reconcile_deliveries->>reconcile_deliveries: compare observed identities and comment IDs
  reconcile_deliveries->>DeliveryReconciliation: ordered receipts and confirmed head
Loading

Possibly related PRs

Suggested labels: enhancement

Poem

A rabbit checks each comment’s place,
Then sorts receipts with measured pace.
States advance in line,
Cleanup records sign,
And invalid paths leave no trace.

🚥 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 addition of the transactional delivery contract.
Description check ✅ Passed The description covers the change, rationale, verification results, known limitations, and scope boundary in substantial detail.
✨ 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/issue765a-delivery-contract

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 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: 9

🤖 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 `@src/delivery_transaction.rs`:
- Around line 334-340: Define a distinct DELIVERY_RECONCILIATION_SCHEMA constant
for reconciliation documents, then update the DeliveryReconciliation
construction to assign that constant to schema instead of
DELIVERY_RECEIPT_SCHEMA. Leave DeliveryReceipt schema assignments unchanged so
consumers can distinguish the two document shapes.
- Around line 456-494: The legal_transition matrix is missing lifecycle terminal
edges, while record_failure and finish_cleanup bypass it with direct state
assignments. Add Planned -> Failed, CleanupAttempted -> CleanedUp, and
CleanupAttempted -> Failed to legal_transition, then update record_failure and
finish_cleanup to use transition for those state changes so the matrix remains
the single state-machine definition.
- Around line 823-847: Extend
reconciliation_rejects_duplicate_or_malformed_comment_ids with a case using two
distinct planned deliveries whose observed entries share the same GitHub comment
ID, so canonical_planned_deliveries succeeds and the observed-set duplicate
guard is reached. Assert the exact “duplicate GitHub comment id in returned
delivery set” error instead of a broad duplicate substring.
- Around line 158-166: Route deserialization for DeliveryTransaction,
PlannedDelivery, and ObservedDelivery through validation instead of deriving
direct Deserialize implementations. Add raw mirror representations using
serde(try_from = "...") that convert through the existing constructors or
validators, preserving checks for schema, head bindings, line and side validity,
and source_thread_id restrictions.
- Around line 421-424: Update validate_head_sha to require exactly 40
hexadecimal characters after trimming, while rejecting whitespace, newlines,
branch names, and other malformed values. Keep validate_planned_delivery
validating expected_head before comparing item.exact_head_sha so the existing
wrong-head error behavior remains unchanged.
- Around line 435-445: Update identity_label to append
DeliveryIdentity.expected_body_digest to the generated label, ensuring
deliveries that differ only by digest produce distinct missing and unexpected
labels. Revise the label expectations in the affected tests around the
identity-label and mismatch cases to include the digest.
- Around line 232-257: Update record_failure so it determines and validates the
target state before mutating self.failure or self.state; reject invalid cleanup
transitions, including Planned or already-CleanupAttempted with
cleanup_attempted set, then apply the failure and resulting state together only
after transition legality is established.

In `@src/main.rs`:
- Around line 30-31: Move the
public_delivery_contract_serializes_exact_initial_state test from the separate
delivery_transaction_contract_tests module into the existing inline mod tests
block at the bottom of src/main.rs, then remove the now-unnecessary
delivery_transaction_contract_tests module while preserving the test unchanged.
- Line 28: Update the delivery_transaction module declaration to use the
project’s established private-module plus pub(crate) glob re-export pattern, and
adjust the inline tests’ imports or references so PlannedDelivery resolves
through super without the fully qualified module path.
🪄 Autofix (Beta)

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: 9cf981cf-7996-435f-afe4-0a4bb072c89a

📥 Commits

Reviewing files that changed from the base of the PR and between 1599dd8 and 3280de4.

📒 Files selected for processing (2)
  • src/delivery_transaction.rs
  • src/main.rs

Comment thread src/delivery_transaction.rs Resolved
Comment thread src/delivery_transaction.rs Resolved
Comment thread src/delivery_transaction.rs Resolved
Comment on lines +421 to +424
fn validate_head_sha(value: &str) -> Result<()> {
ensure!(!value.trim().is_empty(), "exact head SHA must be non-empty");
Ok(())
}

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 | 🟡 Minor | ⚡ Quick win

Validate the head SHA format.

validate_head_sha accepts any non-blank string. Values such as "main", " 0123456789abcdef0123456789abcdef01234567", or a value containing a newline all pass, and the newline case corrupts the error text produced at Line 386. This module treats the value as an exact commit identity, so enforce that shape here.

validate_planned_delivery validates only expected_head before comparing item.exact_head_sha, so the existing wrong-head test at Line 649 keeps its bound to head error.

🛡️ Proposed fix to enforce the SHA shape
 fn validate_head_sha(value: &str) -> Result<()> {
     ensure!(!value.trim().is_empty(), "exact head SHA must be non-empty");
+    ensure!(
+        value.len() == 40 && value.chars().all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)),
+        "exact head SHA must be 40 lowercase hex characters"
+    );
     Ok(())
 }
📝 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
fn validate_head_sha(value: &str) -> Result<()> {
ensure!(!value.trim().is_empty(), "exact head SHA must be non-empty");
Ok(())
}
fn validate_head_sha(value: &str) -> Result<()> {
ensure!(!value.trim().is_empty(), "exact head SHA must be non-empty");
ensure!(
value.len() == 40
&& value
.chars()
.all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)),
"exact head SHA must be 40 lowercase hex characters"
);
Ok(())
}
🤖 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/delivery_transaction.rs` around lines 421 - 424, Update validate_head_sha
to require exactly 40 hexadecimal characters after trimming, while rejecting
whitespace, newlines, branch names, and other malformed values. Keep
validate_planned_delivery validating expected_head before comparing
item.exact_head_sha so the existing wrong-head error behavior remains unchanged.

Comment thread src/delivery_transaction.rs Resolved
Comment thread src/delivery_transaction.rs Resolved
Comment thread src/delivery_transaction.rs Resolved
Comment thread src/main.rs
mod config;
use config::*;
mod builtin;
pub mod delivery_transaction;

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 | 🟠 Major | ⚡ Quick win

Wire the module with the project glob re-export pattern.

The repository wires modules as mod x; pub(crate) use x::*; so that the inline mod tests resolves the types through use super::{...}. Line 28 declares pub mod delivery_transaction; with no re-export, which is why Line 38 must name super::delivery_transaction::PlannedDelivery::new in full. Follow the established pattern.

As per coding guidelines: "Modules are wired via mod x; pub(crate) use x::*; glob re-exports to keep the inline mod tests resolving through use super::{...}".

♻️ Proposed wiring change
-pub mod delivery_transaction;
+mod delivery_transaction;
+pub(crate) use delivery_transaction::*;
📝 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
pub mod delivery_transaction;
mod delivery_transaction;
pub(crate) use delivery_transaction::*;
🤖 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/main.rs` at line 28, Update the delivery_transaction module declaration
to use the project’s established private-module plus pub(crate) glob re-export
pattern, and adjust the inline tests’ imports or references so PlannedDelivery
resolves through super without the fully qualified module path.

Source: Coding guidelines

Comment thread src/main.rs Outdated
Comment on lines +30 to +31
#[cfg(test)]
mod delivery_transaction_contract_tests {

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 | 🟠 Major | ⚡ Quick win

Move this test into the mod tests block.

Lines 30-60 add a second test module, delivery_transaction_contract_tests. The repository keeps unit tests for src/main.rs in the single inline mod tests at the bottom of the file. Move public_delivery_contract_serializes_exact_initial_state into that block.

As per coding guidelines: "Integration tests live in tests/cli.rs; unit tests in the mod tests at the bottom of src/main.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 `@src/main.rs` around lines 30 - 31, Move the
public_delivery_contract_serializes_exact_initial_state test from the separate
delivery_transaction_contract_tests module into the existing inline mod tests
block at the bottom of src/main.rs, then remove the now-unnecessary
delivery_transaction_contract_tests module while preserving the test unchanged.

Source: Coding guidelines

@github-actions github-actions 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.

Decision

  • Needs reviewer attention before upstream: findings remain.

Confirmed findings

  • DeliveryReconciliation.schema is set to DELIVERY_RECEIPT_SCHEMA, identical to DeliveryReceipt.schema. Consumers dispatching on schema cannot distinguish a reconciliation envelope from a single receipt. Define DELIVERY_RECONCILIATION_SCHEMA and use it here.
  • pub mod delivery_transaction; deviates from repo glob re-export pattern mod x; pub(crate) use x::*;. Forces test at line 38 to use full super::delivery_transaction::PlannedDelivery::new path. Apply the standard wiring.
  • legal_transition omits Planned->Failed and CleanupAttempted->{CleanedUp,Failed}. If #765B wires a Python verifier that mirrors this matrix, the mirror will drift; route finish_cleanup / record_failure through transition() and extend the matrix so the Rust and the later verifier twin describe the same state machine.
  • Route DeliveryTransaction, PlannedDelivery, and ObservedDelivery through validation on deserialization via #[serde(try_from = "...")] over raw mirrors; derived Deserialize currently bypasses every invariant (head, side, line, schema, action/thread pairing). PR body overclaims that the contract is closed.
  • Compute next state, validate legal_transition, then assign self.failure and self.state together so a rejected transition cannot leave a Planned or CleanupAttempted transaction with a recorded failure. Currently self.failure = Some(...) precedes the transition call.
  • record_failure must compute next state and validate legality BEFORE assigning self.failure. Current order leaks state (state=Planned, failure=Some(..)) when transition fails. Compute next, call ensure!(legal_transition), then assign failure and state together.
  • Add a test asserting Planned->Failed is legal and that record_failure sets state to Failed atomically with failure; current matrix test pins a machine that omits this terminal edge.
  • record_failure mutates self.failure before calling self.transition(...). If cleanup_attempted is true from a non-edge state (Planned, or already CleanupAttempted), transition returns Err after the mutation, leaving failure recorded with no matching state. Add a Planned->Failed terminal edge and compute next state before applying both fields so an upstream Python verifier can mirror a single 'failure recorded iff transition succeeded' invariant.

Confirmed findings

  • Deserialize bypasses all validators; schema/head/line/side/thread invariants are not enforced on read path.
  • record_failure mutates self.failure before transitioning; (Planned, cleanup_attempted=true) returns error leaving Planned + Some(failure).
  • DeliveryReconciliation.schema uses DELIVERY_RECEIPT_SCHEMA, indistinguishable from a single receipt; consumers dispatching on schema cannot differentiate.

Verification questions

[review body truncated; see review artifacts]

[review body truncated; see review artifacts]

planned_count: planned.len(),
observed_count: observed.len(),
receipts,
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[source-route] DeliveryReconciliation.schema is set to DELIVERY_RECEIPT_SCHEMA, identical to DeliveryReceipt.schema. Consumers dispatching on schema cannot distinguish a reconciliation envelope from a single receipt. Define DELIVERY_RECONCILIATION_SCHEMA and use it here.

Comment thread src/main.rs
mod config;
use config::*;
mod builtin;
pub mod delivery_transaction;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[source-route] pub mod delivery_transaction; deviates from repo glob re-export pattern mod x; pub(crate) use x::*;. Forces test at line 38 to use full super::delivery_transaction::PlannedDelivery::new path. Apply the standard wiring.

}
}

fn legal_transition(current: &DeliveryTransactionState, next: &DeliveryTransactionState) -> bool {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[contract-mirror] legal_transition omits Planned->Failed and CleanupAttempted->{CleanedUp,Failed}. If #765B wires a Python verifier that mirrors this matrix, the mirror will drift; route finish_cleanup / record_failure through transition() and extend the matrix so the Rust and the later verifier twin describe the same state machine.

state: DeliveryTransactionState,
failure: Option<DeliveryFailure>,
cleanup: CleanupOutcome,
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[correctness] Route DeliveryTransaction, PlannedDelivery, and ObservedDelivery through validation on deserialization via #[serde(try_from = "...")] over raw mirrors; derived Deserialize currently bypasses every invariant (head, side, line, schema, action/thread pairing). PR body overclaims that the contract is closed.

} else {
self.state = DeliveryTransactionState::Failed;
}
Ok(())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[correctness] Compute next state, validate legal_transition, then assign self.failure and self.state together so a rejected transition cannot leave a Planned or CleanupAttempted transaction with a recorded failure. Currently self.failure = Some(...) precedes the transition call.

Ok(())
}

pub fn finish_cleanup(&mut self, outcome: CleanupOutcome) -> Result<()> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[opposition] record_failure must compute next state and validate legality BEFORE assigning self.failure. Current order leaks state (state=Planned, failure=Some(..)) when transition fails. Compute next, call ensure!(legal_transition), then assign failure and state together.

}

#[test]
fn legal_transition_matrix_covers_success_and_cleanup_paths() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[tests-red-green] Add a test asserting Planned->Failed is legal and that record_failure sets state to Failed atomically with failure; current matrix test pins a machine that omits this terminal edge.

self.state,
DeliveryTransactionState::ReceiptsPersisted
| DeliveryTransactionState::CleanedUp
| DeliveryTransactionState::Failed

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[contract-mirror] record_failure mutates self.failure before calling self.transition(...). If cleanup_attempted is true from a non-edge state (Planned, or already CleanupAttempted), transition returns Err after the mutation, leaving failure recorded with no matching state. Add a Planned->Failed terminal edge and compute next state before applying both fields so an upstream Python verifier can mirror a single 'failure recorded iff transition succeeded' invariant.

@codecov

codecov Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.33749% with 20 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/delivery_transaction.rs 98.33% 20 Missing ⚠️

📢 Thoughts on this report? Let us know!

@coderabbitai coderabbitai Bot added the enhancement New feature or request label Aug 4, 2026

@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: 4

Caution

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

⚠️ Outside diff range comments (1)
src/delivery_transaction.rs (1)

801-824: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Keep metadata-dependent states out of transition.

The new edges let public DeliveryTransaction::transition enter Failed or finish cleanup without setting failure or cleanup. For example, Planned -> Failed serializes with failure: null, but RawDeliveryTransaction::try_from rejects that object. Restrict transition to invariant-preserving states. Use record_failure and finish_cleanup for failure and cleanup states.

🤖 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/delivery_transaction.rs` around lines 801 - 824, The public
DeliveryTransaction::transition method must not permit transitions into
metadata-dependent Failed or cleanup-completion states, since those transitions
bypass required failure or cleanup metadata. Remove the affected Planned ->
Failed and CleanupAttempted -> CleanedUp/Failed edges from transition, and
require callers to use record_failure and finish_cleanup for those state changes
while preserving only invariant-safe transitions.
🤖 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 14544-14545: In the suppressions.toml file, locate all pairs of
consecutive `[[suppressions]]` array-table headers where the first header has no
fields beneath it and the second header precedes the actual suppression fields
like kind. Remove the first duplicate `[[suppressions]]` header from each pair
to ensure each suppression entry has exactly one header followed by its complete
set of fields.

In `@src/delivery_transaction.rs`:
- Around line 441-453: Validate that a failed cleanup outcome carries a
non-empty reason before assigning self.cleanup and self.state in the cleanup
transition flow. Also update validate_delivery_transaction and the transaction
deserialization path to reject CleanupOutcome::Failed with an empty reason,
while preserving successful cleanup handling.
- Around line 575-597: Add a review_id field to the DeliveryReconciliation
envelope and ensure reconcile_deliveries populates it from its single input
review_id. In the receipt-validation loop around validate_delivery_receipt,
require every receipt.review_id to equal the envelope’s review_id before
accepting the reconciliation, while preserving the existing identity,
comment-ID, and ordering checks.
- Around line 912-913: Move the unit test suite containing
contract_round_trips_each_serialized_shape_and_lifecycle_state from the
delivery_transaction.rs test module into the mod tests block at the bottom of
src/main.rs. Keep these tests as unit tests there, and reserve tests/cli.rs
exclusively for integration tests.

---

Outside diff comments:
In `@src/delivery_transaction.rs`:
- Around line 801-824: The public DeliveryTransaction::transition method must
not permit transitions into metadata-dependent Failed or cleanup-completion
states, since those transitions bypass required failure or cleanup metadata.
Remove the affected Planned -> Failed and CleanupAttempted -> CleanedUp/Failed
edges from transition, and require callers to use record_failure and
finish_cleanup for those state changes while preserving only invariant-safe
transitions.
🪄 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: c1f671f9-ee01-480d-9a52-0fc6ec9b283b

📥 Commits

Reviewing files that changed from the base of the PR and between 3280de4 and 6781e80.

📒 Files selected for processing (3)
  • .ripr/suppressions.toml
  • src/delivery_transaction.rs
  • src/main.rs
💤 Files with no reviewable changes (1)
  • src/main.rs

Comment thread .ripr/suppressions.toml Resolved
Comment thread src/delivery_transaction.rs Resolved
Comment thread src/delivery_transaction.rs Resolved
Comment thread src/delivery_transaction.rs Resolved
@EffortlessSteven
EffortlessSteven marked this pull request as ready for review August 4, 2026 10:41
@EffortlessSteven
EffortlessSteven merged commit bf15a07 into main Aug 4, 2026
5 checks passed
@EffortlessSteven
EffortlessSteven deleted the codex/issue765a-delivery-contract branch August 4, 2026 10:44

@github-actions github-actions 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.

Decision

  • Needs reviewer attention before upstream: findings remain.

Confirmed findings

  • Schema-collision risk route unresolved.
  • identity_label format includes expected_body_digest as 7th colon-separated field; earlier PR-body versions omitted digest.
  • Reconciliation does not enforce envelope review_id binding: a deserialized DeliveryReconciliation can mix valid receipts from different reviews only via raw JSON construction (validate_delivery_reconciliation loop does check receipt.review_id == reconciliation.review_id, so it IS closed). Note this as verified, not as finding.
  • Empty cleanup-failure-reason guard test (failure_after_creation_records_cleanup_success_or_failure) only checks error string at the deserialization site; the in-memory finish_cleanup path is asserted separately but the ordering of validation-before-mutation oracle is implicit.
  • PR body asserts 'validated JSON round-trips'; the contract_round_trips_each_serialized_shape_and_lifecycle_state test exercises inline+reply receipts but not Reply-to-Inline or duplicate-comment-id reconciliation paths the seeded thread flagged as untested. Coverage is 98.33% with 20 lines missing per codecov; missing lines likely include reconciliation edge cases.

Verification questions

  • Confirm identity label format claim:action:path:line:side:thread:digest is asserted in tests but identity_label only emits 6 colon-separated fields (omits digest); seeded coderabbit also flagged it.
  • Confirm duplicate observed comment-id guard at lines 293-297 is unreachable: reconciliation_rejects_duplicate_or_malformed_comment_ids passes a planned slice containing first twice so canonical_planned_deliveries fails on 'duplicate planned delivery identity' first.
  • Confirm public re-export pattern deviation.
  • Confirm pub mod delivery_transaction; deviates from the repo's standard mod x; pub(crate) use x::*; glob re-export pattern, forcing the src/main.rs test to spell super::delivery_transaction::PlannedDelivery::new.
  • Confirm unit-test placement in src/main.rs (lines ~30-60 delivery_transaction_contract_tests) belongs in the existing inline mod tests at the bottom of the file; tests/cli.rs is reserved for integration. Repo coding guideline says unit tests live in mod tests at the bottom of src/main.rs.
  • Confirm suppressions duplicate-header concern remains: 42 added entries are well-formed but suppress a wide surface (incl. 14 legal_transition arm entries .1..13 sharing one finding_id base). Re-verify after any edit.

Verification questions

Refuted

Proof results

[review body truncated; see review artifacts]

[review body truncated; see review artifacts]

@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: 7a0c20309a

ℹ️ 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 on lines +386 to +389
!matches!(
next,
DeliveryTransactionState::Failed | DeliveryTransactionState::CleanedUp
),

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 Block direct entry into CleanupAttempted

When a transaction is PendingReviewCreated, transition(CleanupAttempted) is legal even though it does not populate failure; calling finish_cleanup(Succeeded) afterward produces CleanedUp with failure: None. That value serializes successfully but is rejected by this module's own deserializer, which requires cleaned-up transactions to carry a failure. Include CleanupAttempted among the metadata-dependent states so callers must enter it through record_failure.

Useful? React with 👍 / 👎.

Comment on lines +720 to +723
ensure!(
identities.insert(DeliveryIdentity::from(item)),
"duplicate planned delivery identity for claim {}",
item.claim_id

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 Reject multiple deliveries for the same claim

When two planned items share a claim_id but differ in path, action, line, thread, or digest, their full DeliveryIdentity values differ, so both pass this set check and reconciliation can confirm two public comments for one claim. This contradicts the existing public-surface invariant in src/review_experience.rs:405-413 that each claim has at most one human-facing location; track claim IDs separately and reject duplicates before sorting.

Useful? React with 👍 / 👎.

Comment on lines +769 to +771
fn validate_head_sha(value: &str) -> Result<()> {
ensure!(!value.trim().is_empty(), "exact head SHA must be non-empty");
Ok(())

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 Require an immutable object ID for exact heads

When a caller supplies a symbolic or abbreviated value such as main or deadbeef, this validation accepts it, and reconciliation later copies that same value into confirmed_head_sha, producing a receipt that appears confirmed without being bound to an immutable exact commit. Because these receipts are intended to prevent stale-head delivery, reject non-canonical Git object IDs rather than checking only for non-whitespace input.

Useful? React with 👍 / 👎.

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

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant