From 335637fc0f42b1f3ced704ff7300259e79cec21c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 03:47:23 +1300 Subject: [PATCH 01/10] Recognize archived addressed-thread metadata in Hosted completion proof --- dev-tools/pr_review/hosted.py | 260 +++++++++++++++++- dev-tools/pr_review/runtime.py | 13 +- .../test_pr_review_evidence_hosted.py | 199 ++++++++++++++ 3 files changed, 469 insertions(+), 3 deletions(-) diff --git a/dev-tools/pr_review/hosted.py b/dev-tools/pr_review/hosted.py index 7dddb638ed..1ec845af8c 100644 --- a/dev-tools/pr_review/hosted.py +++ b/dev-tools/pr_review/hosted.py @@ -10,7 +10,7 @@ import re import stat import tempfile -from collections.abc import Callable +from collections.abc import Callable, Mapping from dataclasses import dataclass from datetime import datetime, timedelta, timezone from pathlib import Path @@ -1532,6 +1532,236 @@ def _is_finished_action_response(body: str, *, allow_action_wrapper: bool) -> bo ) +_ADDRESSED_COMMIT_ANNOTATION = re.compile( + r"(?:\r?\n){2}āœ… Addressed in commits ([0-9a-f]{7,40}) to ([0-9a-f]{7,40})\Z", + re.IGNORECASE, +) + + +def _archived_completed_thread_bodies( + repo: str, + pr_number: int, + head: str, + record: Mapping[str, Any] | None, + current_record_path: str | Path | None, +) -> dict[int, tuple[str, str]]: + """Read immutable prior Hosted thread bodies for exact trigger attribution.""" + + if not isinstance(record, Mapping): + return {} + current_attempt_id = record.get("sqlite_attempt_id") + trigger = record.get("trigger") + trigger_id = trigger.get("id") if isinstance(trigger, Mapping) else None + trigger_at = parse_timestamp(trigger.get("created_at")) if isinstance(trigger, Mapping) else None + if ( + not isinstance(current_attempt_id, str) + or not current_attempt_id + or type(trigger_id) is not int + or trigger_id <= 0 + or trigger_at is None + or not isinstance(record.get("head_sha"), str) + or record["head_sha"].casefold() != head.casefold() + ): + return {} + + selected_record = Path(current_record_path) if current_record_path is not None else default_trigger_record_path( + repo, pr_number + ) + if selected_record.is_symlink(): + return {} + common = _trigger_record_common_for_path(selected_record, repo, pr_number) + if common is None: + return {} + selected_state = state_path(common) + if selected_state.is_symlink() or not selected_state.is_dir(): + return {} + database = sqlite_state_path(selected_state) + try: + database_stat = database.stat(follow_symlinks=False) + except FileNotFoundError: + return {} + if database.is_symlink() or not stat.S_ISREG(database_stat.st_mode): + return {} + + try: + records = SqliteReviewRecords(database) + current_attempt = records.attempt(current_attempt_id) + attempt_history = records.attempt_history(pr_number) + current_history = [item for item in attempt_history if item.get("attempt_id") == current_attempt_id] + current_head = current_attempt.get("candidate_sha") + if ( + current_attempt.get("source_pr") != pr_number + or current_attempt.get("channel") != "hosted" + or not isinstance(current_head, str) + or current_head.casefold() != head.casefold() + or len(current_history) != 1 + or current_history[0].get("trigger_id") != str(trigger_id) + ): + return {} + + candidates: dict[int, list[tuple[str, str]]] = {} + for attempt in attempt_history: + candidate_head = attempt.get("candidate_sha") + started_at = parse_timestamp(attempt.get("started_at")) + finished_at = parse_timestamp(attempt.get("finished_at")) + if ( + attempt.get("channel") != "hosted" + or attempt.get("state") != "completed" + or not isinstance(candidate_head, str) + or not EXACT_SHA.fullmatch(candidate_head) + or started_at is None + or finished_at is None + or finished_at >= trigger_at + ): + continue + attempt_id = attempt.get("attempt_id") + provider_review_id = attempt.get("provider_review_id") + archived_trigger_id = attempt.get("trigger_id") + if ( + not isinstance(attempt_id, str) + or not attempt_id + or not isinstance(provider_review_id, str) + or not provider_review_id.isdecimal() + or not isinstance(archived_trigger_id, str) + or not archived_trigger_id.isdecimal() + ): + continue + artifacts = records.attempt_artifacts(attempt_id) + try: + metadata = json.loads(artifacts.get("metadata", "")) + archived = json.loads(artifacts.get("hosted_comments", "")) + reviews = json.loads(artifacts.get("hosted_review", "")) + except (TypeError, ValueError, json.JSONDecodeError): + continue + observed_at = parse_timestamp(metadata.get("observed_at")) if isinstance(metadata, dict) else None + metadata_repository = metadata.get("repository") if isinstance(metadata, dict) else None + metadata_head = metadata.get("head_sha") if isinstance(metadata, dict) else None + if ( + not isinstance(metadata, dict) + or metadata.get("state") != "completed" + or metadata.get("terminal") is not True + or metadata.get("attributable") is not True + or not isinstance(metadata_repository, str) + or metadata_repository.casefold() != repo.casefold() + or metadata.get("pull_request") != pr_number + or not isinstance(metadata_head, str) + or metadata_head.casefold() != candidate_head.casefold() + or type(metadata.get("trigger_id")) is not int + or str(metadata["trigger_id"]) != archived_trigger_id + or type(metadata.get("response_id")) is not int + or str(metadata["response_id"]) != provider_review_id + or observed_at is None + or observed_at != finished_at + or not isinstance(archived, dict) + or not isinstance(archived.get("comments"), list) + or not isinstance(archived.get("review_threads"), list) + or not isinstance(reviews, list) + ): + continue + + matching_reviews = [ + item + for item in reviews + if isinstance(item, dict) + and immutable_database_id(item) == metadata["response_id"] + and is_coderabbit_login((item.get("author") or {}).get("login")) + and item.get("state") != "DISMISSED" + and isinstance((item.get("commit") or {}).get("oid"), str) + and (item.get("commit") or {}).get("oid").casefold() == candidate_head.casefold() + ] + matching_triggers = [ + item + for item in archived["comments"] + if isinstance(item, dict) and immutable_database_id(item) == int(archived_trigger_id) + ] + if ( + len(matching_reviews) != 1 + or len(matching_triggers) != 1 + or is_coderabbit_login((matching_triggers[0].get("author") or {}).get("login")) + or normalize_command(matching_triggers[0].get("body") or "") != FULL_COMMAND + ): + continue + archived_trigger_at = parse_timestamp(matching_triggers[0].get("createdAt")) + review_submitted_at = parse_timestamp(matching_reviews[0].get("submittedAt")) + if ( + archived_trigger_at is None + or archived_trigger_at > finished_at + or review_submitted_at is None + or review_submitted_at < archived_trigger_at + or review_submitted_at > finished_at + ): + continue + + for thread in archived["review_threads"]: + comments = thread.get("comments") if isinstance(thread, dict) else None + nodes = comments.get("nodes") if isinstance(comments, dict) else None + if not isinstance(nodes, list): + continue + for item in nodes: + if not isinstance(item, dict) or not is_coderabbit_login((item.get("author") or {}).get("login")): + continue + comment_id = immutable_database_id(item) + created_at = item.get("createdAt") + created = parse_timestamp(created_at) + body = item.get("body") + if ( + comment_id is None + or not isinstance(created_at, str) + or created is None + or created < archived_trigger_at + or created > finished_at + or not isinstance(body, str) + ): + continue + candidates.setdefault(comment_id, []).append((created_at, body)) + + result: dict[int, tuple[str, str]] = {} + for comment_id, baselines in candidates.items(): + if len(baselines) == 1: + result[comment_id] = baselines[0] + except Exception: # noqa: BLE001 - unavailable or incompatible archive must remain fail closed + return {} + return result + + +def _addressed_thread_update_matches_archive( + item: dict[str, Any], + head: str, + after: datetime, + before: datetime | None, + archived_bodies: Mapping[int, tuple[str, str]], +) -> bool: + """Accept only the exact known addressed footer appended to an archived finding.""" + + comment_id = immutable_database_id(item) + if comment_id is None: + return False + archived = archived_bodies.get(comment_id) + body = item.get("body") + created_at = item.get("createdAt") + updated = parse_timestamp(item.get("updatedAt")) + created = parse_timestamp(created_at) + if ( + archived is None + or not isinstance(body, str) + or not isinstance(created_at, str) + or created_at != archived[0] + or not isinstance(archived[1], str) + or created is None + or created >= after + or updated is None + or updated <= after + or (before is not None and updated >= before) + ): + return False + annotation = _ADDRESSED_COMMIT_ANNOTATION.search(body) + return ( + annotation is not None + and annotation.group(2).casefold() == head[: len(annotation.group(2))].casefold() + and body[: annotation.start()] == archived[1] + ) + + def _summary_has_explicit_incompleteness(body: str) -> bool: text = _unquoted(body) not_reviewed_counts = [int(match.group(1)) for match in FILE_NOT_REVIEWED_COUNT.finditer(text)] @@ -1815,6 +2045,10 @@ def finished_reply_without_findings( after: datetime, response_id: int | None, before: datetime | None = None, + record: Mapping[str, Any] | None = None, + current_record_path: str | Path | None = None, + repo: str | None = None, + pr_number: int | None = None, ) -> bool: """Accept CodeRabbit's terminal full-review reply when its complete window is empty. @@ -1893,6 +2127,7 @@ def in_window(value: Any) -> bool | None: submitted_in_window = in_window(item.get("submittedAt")) if submitted_in_window is None or submitted_in_window: return False + archived_bodies: dict[int, tuple[str, str]] | None = None for thread in connections["reviewThreads"]: comments = thread.get("comments") nodes = comments.get("nodes") if isinstance(comments, dict) else None @@ -1903,7 +2138,24 @@ def in_window(value: Any) -> bool | None: continue created_in_window = in_window(item.get("createdAt")) updated_in_window = in_window(item.get("updatedAt")) - if created_in_window is None or updated_in_window is None or created_in_window or updated_in_window: + if created_in_window is None or updated_in_window is None: + return False + if created_in_window or updated_in_window: + if not created_in_window and updated_in_window: + if archived_bodies is None: + archived_bodies = ( + _archived_completed_thread_bodies( + repo, + pr_number, + head, + record, + current_record_path, + ) + if isinstance(repo, str) and type(pr_number) is int and pr_number > 0 + else {} + ) + if _addressed_thread_update_matches_archive(item, head, after, before, archived_bodies): + continue return False return True @@ -2083,6 +2335,10 @@ def trigger_state( trigger_dt, immutable_database_id(item), next_dt, + record, + current_record_path, + repo, + pr_number, ): state = ( "ambiguous_retired_predecessor" diff --git a/dev-tools/pr_review/runtime.py b/dev-tools/pr_review/runtime.py index 74d3cc0c2f..731730b2bf 100644 --- a/dev-tools/pr_review/runtime.py +++ b/dev-tools/pr_review/runtime.py @@ -1111,6 +1111,8 @@ def _hosted_zero_reply_proof( checkpoint: evidence.Checkpoint, response_id: int | None, response_duration_seconds: int | None, + repo: str, + pr_number: int, captured_head: str, record: dict[str, Any], payload: dict[str, Any], @@ -1182,7 +1184,14 @@ def _hosted_zero_reply_proof( next_trigger, ) finished_only = hosted.finished_reply_without_findings( - payload, captured_head, trigger_at, response_id, next_trigger + payload, + captured_head, + trigger_at, + response_id, + next_trigger, + record, + repo=repo, + pr_number=pr_number, ) if legacy_summary is None and provider_summary is None and not finished_only: return None @@ -1229,6 +1238,8 @@ def _hosted_trigger_for_checkpoint( checkpoint, state.response_id, state.duration_seconds, + self.repo, + pr, captured_head, record, payload, diff --git a/dev-tools/validation/test_pr_review_evidence_hosted.py b/dev-tools/validation/test_pr_review_evidence_hosted.py index 36f5099858..7b7c91d573 100644 --- a/dev-tools/validation/test_pr_review_evidence_hosted.py +++ b/dev-tools/validation/test_pr_review_evidence_hosted.py @@ -80,6 +80,145 @@ def trigger_record(head: str = HEAD): } +def archived_addressed_reply_fixture(common: Path, *, include_baseline: bool = True): + trigger_at = "2026-09-23T00:02:00Z" + old_trigger_at = "2026-09-23T00:00:50Z" + old_started_at = "2026-09-23T00:00:40Z" + old_finished_at = "2026-09-23T00:01:15Z" + old_body = "An archived CodeRabbit finding.\n\n" + addressed_body = f"{old_body}\n\nāœ… Addressed in commits {'c' * 7} to {HEAD[:7]}" + inline = { + "databaseId": 30, + "author": {"login": "coderabbitai[bot]"}, + "body": addressed_body, + "createdAt": "2026-09-23T00:01:10Z", + "updatedAt": "2026-09-23T00:02:15Z", + } + old_review = { + "databaseId": 20, + "author": {"login": "coderabbitai[bot]"}, + "body": "\nReviewing the archived candidate.", + "state": "COMMENTED", + "submittedAt": old_finished_at, + "commit": {"oid": BASE}, + } + old_comments = { + "comments": [ + comment(9, "owner", hosted.FULL_COMMAND, old_trigger_at), + ], + "review_threads": ( + [ + { + "comments": { + "nodes": [ + { + **inline, + "body": old_body, + "createdAt": inline["createdAt"], + "updatedAt": old_finished_at, + } + ] + } + } + ] + if include_baseline + else [] + ), + } + old_metadata = { + "state": "completed", + "terminal": True, + "attributable": True, + "repository": REPO, + "pull_request": PR, + "head_sha": BASE, + "trigger_id": 9, + "response_id": 20, + "observed_at": old_finished_at, + } + + state_dir = common / "firemud" / "pr-review-stack.json" + state_dir.mkdir(parents=True) + database = common / "firemud" / "pr-review-stack.sqlite3" + SqliteStateStore(database).update(lambda state: state) + records = SqliteReviewRecords(database) + records.bootstrap() + records.start_attempt( + attempt_id="old-hosted-attempt", + source_pr=PR, + channel="hosted", + candidate_sha=BASE, + started_at=old_started_at, + ) + records.finish_attempt( + "old-hosted-attempt", + state="completed", + finished_at=old_finished_at, + trigger_id="9", + provider_review_id="20", + artifacts={ + "hosted_review": json.dumps([old_review]), + "hosted_comments": json.dumps(old_comments), + "metadata": json.dumps(old_metadata), + }, + ) + records.start_attempt( + attempt_id="current-hosted-attempt", + source_pr=PR, + channel="hosted", + candidate_sha=HEAD, + started_at="2026-09-23T00:01:50Z", + ) + records.finish_attempt( + "current-hosted-attempt", + state="ambiguous", + finished_at="2026-09-23T00:02:08Z", + trigger_id="10", + provider_review_id="11", + artifacts={ + "hosted_review": "[]", + "hosted_comments": json.dumps({"comments": []}), + "metadata": json.dumps({"state": "ambiguous"}), + }, + ) + + trigger = comment(10, "owner", hosted.FULL_COMMAND, trigger_at) + summary = comment( + 12, + "coderabbitai[bot]", + "No actionable comments were generated in the recent review.\n" + f"Reviewing files that changed from the base of the PR and between {BASE} and {HEAD}.", + "2026-09-23T00:01:40Z", + ) + summary["updatedAt"] = "2026-09-23T00:02:30Z" + response = comment( + 11, + "coderabbitai[bot]", + "\n" + f"\n" + "
\nāœ… Action performed\n" + "Full review finished.\n
", + "2026-09-23T00:02:08Z", + ) + response["updatedAt"] = "2026-09-23T00:02:20Z" + payload = review_payload( + [trigger, summary, response], + threads=[{"comments": {"nodes": [inline]}}], + ) + record = trigger_record() + record["sqlite_attempt_id"] = "current-hosted-attempt" + record["trigger"].update( + { + "id": 10, + "created_at": trigger_at, + "url": trigger["url"], + } + ) + record_path = hosted.default_trigger_record_path(REPO, PR, common) + record_path.parent.mkdir(parents=True, exist_ok=True) + return payload, record, record_path + + class GithubAndEvidenceTests(unittest.TestCase): def test_cli_result_exposes_human_duration_without_changing_seconds_or_marker(self): result = ReviewResult( @@ -1749,6 +1888,66 @@ def test_finished_reply_with_empty_complete_history_is_clean_completion(self): with self.assertRaisesRegex(ValueError, "invalid full-review identity"): hosted.trigger_state(REPO, PR, review_payload([trigger, finished]), bool_record) + def test_finished_reply_accepts_only_exact_archived_addressed_thread_updates(self): + with tempfile.TemporaryDirectory() as directory: + payload, record, record_path = archived_addressed_reply_fixture(Path(directory)) + + state = hosted.trigger_state(REPO, PR, payload, record, record_path) + + self.assertEqual(state.state, "completed") + self.assertTrue(state.attributed) + self.assertEqual(state.response_id, 11) + + def test_finished_reply_keeps_unproven_or_changed_thread_output_ambiguous(self): + cases = ( + ("unknown baseline", False, None), + ("modified archived body", True, "modified_body"), + ("addressed range ends on another head", True, "mismatched_range"), + ("new inline comment", True, "new_comment"), + ("positive finding count", True, "positive_count"), + ("incomplete coverage", True, "incomplete_coverage"), + ("mismatched summary head", True, "mismatched_summary_head"), + ) + for label, include_baseline, mutation in cases: + with self.subTest(case=label), tempfile.TemporaryDirectory() as directory: + payload, record, record_path = archived_addressed_reply_fixture( + Path(directory), include_baseline=include_baseline + ) + thread_nodes = payload["data"]["repository"]["pullRequest"]["reviewThreads"]["nodes"][0][ + "comments" + ]["nodes"] + if mutation == "modified_body": + thread_nodes[0]["body"] = thread_nodes[0]["body"].replace( + "An archived CodeRabbit finding.", "A changed CodeRabbit finding." + ) + elif mutation == "mismatched_range": + thread_nodes[0]["body"] = thread_nodes[0]["body"].replace( + f"to {HEAD[:7]}", f"to {BASE[:7]}" + ) + elif mutation == "new_comment": + thread_nodes.append( + { + "databaseId": 31, + "author": {"login": "coderabbitai[bot]"}, + "body": "A new inline finding.", + "createdAt": "2026-09-23T00:02:16Z", + "updatedAt": "2026-09-23T00:02:16Z", + } + ) + elif mutation in {"positive_count", "incomplete_coverage", "mismatched_summary_head"}: + issue_comments = payload["data"]["repository"]["pullRequest"]["comments"]["nodes"] + summary = next(item for item in issue_comments if item["databaseId"] == 12) + if mutation == "positive_count": + summary["body"] += "\n**Actionable comments posted: 1**" + elif mutation == "incomplete_coverage": + summary["body"] += "\nFiles not reviewed: 3." + else: + summary["body"] = summary["body"].replace(HEAD, BASE) + + state = hosted.trigger_state(REPO, PR, payload, record, record_path) + + self.assertEqual(state.state, "ambiguous") + def test_active_acknowledgement_does_not_hide_clean_finished_result(self): trigger = comment(10, "owner", hosted.FULL_COMMAND, "2026-09-23T00:01:00Z") acknowledgement = comment(11, "coderabbitai", "Full review triggered", "2026-09-23T00:01:08Z") From 9ba0752b9e36faaecd1483fe19e1d9f579b422c6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 04:16:10 +1300 Subject: [PATCH 02/10] feat(review): support exact additional rounds --- design/developer-workflows/pr-lifecycle.md | 2 +- dev-tools/pr_review/README.md | 2 + dev-tools/pr_review/cli.py | 7 + dev-tools/pr_review/controller.py | 47 +++- .../pr_review/sqlite_provider_imports.py | 2 + .../validation/test_pr_review_cli_runner.py | 23 ++ .../validation/test_pr_review_controller.py | 220 ++++++++++++++++++ .../test_pr_review_sqlite_provider_imports.py | 27 ++- 8 files changed, 313 insertions(+), 17 deletions(-) diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index 726f860a62..22b3009ac6 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -19,7 +19,7 @@ Use this guide for pull-request status, review handling, CI, Renovate, merging, - If that exact legacy transition is followed by a fresh review and a later coherent fix head, reauthorize only the same immutable fingerprints with `dev-tools/pr-review decide transition --reauthorize --pr --head --reason ""`. The controller requires a prior transition, verifies every carried record again, and requires every other observation to be normal completed attributable anchored evidence; newer evidence remains counting and subject to ordinary reconciliation and judgment. A changed head without this explicit reauthorization remains blocked, and the command never creates a checkpoint or consumes review quota. - A single previously audited Hosted fingerprint that is absent from the complete current history may be retired only with `--reauthorize --retire-missing-hosted-fingerprint `. This requires the exact prior fingerprint, coherent current topology, complete available Hosted trigger records and paginated GitHub review/comment history, terminal and uniquely attributable responses, no active or unresolved reservation, and no unresolved actionable findings; any missing or ambiguous proof remains held. The fingerprint stays in the transition audit and remains non-counting if it later reappears. This decision never reconstructs evidence or creates a checkpoint and does not grant review, taper, finding-count, or merge-readiness credit. - Record an explicit channel judgment with `dev-tools/pr-review decide judgment retain|reopen --pr --channel hosted|cli --head --checkpoint --reason ""`. Retain confirms the verified equivalent patch for request and queue safety; reopen explicitly requires fresh review without deleting historical completed taper and resets the taper streak at the bound checkpoint. For CLI, a reopen may bind the latest complete modern checkpoint to a proven descendant live head, but carries no new review credit until later completed results arrive. A narrow channel policy override uses `dev-tools/pr-review decide policy --pr --head --checkpoint --hosted-zero-useful --reason ""` or `--cli-zero-useful ` (exactly one channel); it sets that channel's zero-useful completion count for the exact checkpoint. -- Extend the existing allocation with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head [--checkpoint ] [--min-additional-completed ] [--max-additional-completed ] [--fresh-taper] --reason ""`. Both bounds count completed, attributable results for that PR and channel beginning at the decision; the optional checkpoint records the observed identity but does not move that count's start. With neither bound, the existing one-result promise remains (`min=1`, `max=1`). A minimum-only allocation has no maximum; a maximum-only allocation has no extra minimum (`min=0`). Without `--fresh-taper`, an allocation after completed taper affects queue eligibility and its additional-result count while preserving the existing historical taper display. Its zero-useful results continue the normal streak. An accepted allocated result resets the active streak at that result, while all earlier checkpoints remain visible with their original counts; after fixes, later zero-useful results can satisfy taper. `--fresh-taper` starts the active streak at the allocation decision immediately; earlier dry results remain visible historical evidence but cannot satisfy it. When both bounds are set, reject `min > max`; the minimum requires that many additional results even after fresh taper, while taper may stop earlier than the maximum once the minimum is met. Rate limits, connection failures, duplicates, partial or ambiguous responses, provisional captures, and other non-counting observations do not consume the count. Hosted and CLI allocations remain independent; request-time identity checks apply only when posting a new review. +- Extend the existing allocation with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head [--checkpoint ] [--min-additional-completed ] [--max-additional-completed ] [--exact-additional-completed ] [--fresh-taper] --reason ""`. Both bounds count completed, attributable results for that PR and channel beginning at the decision; the optional checkpoint records the observed identity but does not move that count's start. With neither bound, the existing one-result promise remains (`min=1`, `max=1`). A minimum-only allocation has no maximum; a maximum-only allocation has no extra minimum (`min=0`). `--exact-additional-completed N` is mutually exclusive with the separate bounds and `--fresh-taper`, and records `min=max=N`, so ordinary taper cannot stop discovery before all `N` results and the cap stops discovery immediately afterward. It preserves the existing taper rather than starting a fresh streak. Use `allocation renew --exact-additional-completed N` to replace an existing allocation or audited human stop explicitly. A verifiable request already admitted at the exact-allocation decision remains in flight and counts only when it completes attributably; ambiguous or unsupported active evidence is refused. Without `--fresh-taper`, an allocation after completed taper affects queue eligibility and its additional-result count while preserving the existing historical taper display. Its zero-useful results continue the normal streak. An accepted allocated result resets the active streak at that result, while all earlier checkpoints remain visible with their original counts; after fixes, later zero-useful results can satisfy taper. `--fresh-taper` starts the active streak at the allocation decision immediately; earlier dry results remain visible historical evidence but cannot satisfy it. When both bounds are set, reject `min > max`; the minimum requires that many additional results even after fresh taper, while taper may stop earlier than the maximum once the minimum is met. Rate limits, connection failures, duplicates, partial or ambiguous responses, provisional captures, and other non-counting observations do not consume the count. Hosted and CLI allocations remain independent; request-time identity checks apply only when posting a new review. - Normal taper can finish before a maximum once the minimum is met. After any additional result with accepted findings, no next request is allowed until those findings, current/outdated threads, actionable summary findings, and fix publication/validation obligations are clear, even if capacity remains. Once the maximum is used, no further request is allowed for that PR/channel; a maximum stop is not taper and does not waive accepted findings or fixes. `status` and `evidence` expose the minimum, maximum, completed count, baseline identity, in-flight results, taper state, and controlling reason. When the maximum is exhausted, the controller derives an audited human-cap stop and advances that channel through its normal selector without a separate `decide stop`, subject to the active-review safety described below. Pending obligations remain source-owned and visible as `cap exhausted; findings pending`; this stop is not taper, current-head review, CI/Smoke proof, or merge readiness. A bounded allocation can be replaced explicitly with `allocation renew` and new bounds; `allocation cancel` removes it. Ordinary fixes never reset its completed count. - When the Overseer deliberately allocates one further completed review before deciding whether to continue, record it before the review with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head --reason ""`. Completed-result counts belong to the PR and channel and survive later identity changes; rate limits, partial, duplicate, and unattributable results do not consume the allocation. Record a human decision to make no further requests with `dev-tools/pr-review decide stop --pr --channel hosted|cli --reason ""`. This audited PR/channel override bypasses the taper gate only for queue advancement; it is not taper completion or proof of review coverage, and it persists across head and parent changes. It requires no completed checkpoint, clean findings, idle provider, or coherent review topology. An already admitted CLI or Hosted run continues with its reservation, capture, attribution, and eventual findings intact; finishing that run does not clear the override. Stop recording and new-request admission share only the short state mutation boundary, while each provider keeps its execution exclusion. Optional `--head` and `--checkpoint` pins must match the observed identities; unavailable optional Git proof is recorded as absent, never fabricated. Existing ambiguity-retention and over-ceiling acknowledgment options record their specific evidence without granting review credit. Discovery can advance only when the same channel has no active provider run. Accepted fixes, pending captures and adjudication, attributable evidence, current and outdated threads, actionable summaries, required CI, runtime proof, ancestry, and merge safety remain independent obligations. A stop overrides taper only and does not manufacture a reviewed head or merge readiness. - For a channel that still needs review, targeting stops at the first held, unstable, unreconciled, over-ceiling, or judgment-blocked PR; it skips PRs whose channel has completed taper or an audited human stop. The narrow exception is a verified terminal, non-counting Hosted response: keep that PR incomplete and visible, but use the next coherent PR's Hosted window if one exists. Do not post another request on the ambiguous PR or grant it taper or merge credit; revisit its evidence or obtain an audited human stop before its merge handoff. Request-time identity and active-review checks still apply before any new request for an incomplete channel. A file-ceiling rejection requires a coherent topology decision; there is no normal incremental-review fallback. diff --git a/dev-tools/pr_review/README.md b/dev-tools/pr_review/README.md index e15fdb9227..3447df5d00 100644 --- a/dev-tools/pr_review/README.md +++ b/dev-tools/pr_review/README.md @@ -12,6 +12,8 @@ The output identifies the SQLite schema and writer build. The live shared cutove For a posted Hosted request, `dev-tools/pr-review wait hosted --pr --trigger-id ` watches only that saved trigger. `--poll-seconds` defaults to 30 and `--max-wait-minutes` to 90. It returns JSON and exit status 0 for an attributable completion, 3 for another terminal result, or 4 when the wait expires; it never posts a request, grants review credit, or retires the trigger. The caller must read the result and use `records sync-hosted --pr ` before adjudicating a completed review. A wait expiration leaves the underlying trigger unchanged. +To require exactly a chosen number of further completed attributable results on one channel, use `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head --exact-additional-completed --reason ""`. Use `allocation renew` instead of `grant` to replace an existing allocation or human stop explicitly. The command records the existing minimum and maximum as the same positive number; it does not start a fresh taper streak. Earlier completed evidence remains historical, while a verifiable request already admitted at the decision remains in flight and consumes one result only if it later completes attributably. Failures, rate limits, and other non-counting results consume none. Discovery continues until all `N` results complete even if ordinary taper was already satisfied or becomes satisfied early, then closes at the exact cap while accepted findings and fixes remain mandatory obligations. + ### Manual Hosted adoption A human-posted Hosted CodeRabbit request can be incorporated without requesting another review: after the review completes, run `dev-tools/pr-review decide trigger-adopt-manual --pr --trigger-id --head `. This verifies the immutable public command, completed response, and current anchor before writing a private attribution record. A queued PR uses its reconciled stack parent; an off-queue PR uses its actual live base branch after matching the live base and head tips to their remote refs. Off-queue adoption leaves the configured review queue unchanged. The command does not post a GitHub comment, create a result checkpoint, or grant taper by itself; adjudicate findings and post the normal public Hosted checkpoint next. A moved head or ambiguous response is refused. diff --git a/dev-tools/pr_review/cli.py b/dev-tools/pr_review/cli.py index d2c828a5ed..e801cb7eac 100644 --- a/dev-tools/pr_review/cli.py +++ b/dev-tools/pr_review/cli.py @@ -408,6 +408,12 @@ def records_database(command: argparse.ArgumentParser) -> None: metavar="N", help="maximum additional completed attributable results after the decision", ) + allocation.add_argument( + "--exact-additional-completed", + type=_positive_int, + metavar="N", + help="require exactly N additional completed attributable results after the decision", + ) allocation.add_argument( "--fresh-taper", action="store_true", @@ -1662,6 +1668,7 @@ def record(current): checkpoint=args.checkpoint, min_additional_completed=args.min_additional_completed, max_additional_completed=args.max_additional_completed, + exact_additional_completed=args.exact_additional_completed, fresh_taper=args.fresh_taper, ), 0 if args.decide_command == "stop": diff --git a/dev-tools/pr_review/controller.py b/dev-tools/pr_review/controller.py index 1faacac900..1ddfd072de 100644 --- a/dev-tools/pr_review/controller.py +++ b/dev-tools/pr_review/controller.py @@ -5607,6 +5607,7 @@ def decide_allocation( checkpoint: str | None = None, min_additional_completed: int | None = None, max_additional_completed: int | None = None, + exact_additional_completed: int | None = None, fresh_taper: bool = False, ) -> dict[str, Any]: """Grant, replace, or cancel a one-result or bounded review allocation.""" @@ -5623,6 +5624,22 @@ def decide_allocation( raise ControllerError("fresh taper selection must be boolean") if checkpoint is not None and (not isinstance(checkpoint, str) or not checkpoint.strip()): raise ControllerError("allocation baseline checkpoint must be a non-empty immutable identity") + if exact_additional_completed is not None and ( + isinstance(exact_additional_completed, bool) + or not isinstance(exact_additional_completed, int) + or exact_additional_completed <= 0 + ): + raise ControllerError("exact additional completed reviews must be a positive integer") + if exact_additional_completed is not None and ( + min_additional_completed is not None or max_additional_completed is not None + ): + raise ControllerError("exact additional completed reviews cannot be combined with minimum or maximum") + if exact_additional_completed is not None and fresh_taper: + raise ControllerError("exact additional completed reviews preserve the existing taper") + exact_replacement = exact_additional_completed is not None + if exact_replacement: + min_additional_completed = exact_additional_completed + max_additional_completed = exact_additional_completed if min_additional_completed is not None and ( isinstance(min_additional_completed, bool) or not isinstance(min_additional_completed, int) @@ -5706,10 +5723,26 @@ def provable_posted_hosted_request(value: Any) -> bool: and self._hosted_anchor_matches(value, pr, current) ) + def exact_in_flight_request(value: Any) -> bool: + if not exact_replacement or _field(value, "channel") not in (None, selected.value): + return False + if selected == policy.Channel.HOSTED: + return self._hosted_active_response_overlaps_cli( + value, + pr, + item.head, + current, + require_response_identity=True, + ) + return self._active_cli_review_overlaps_hosted(value, pr, current) + + def permitted_in_flight_request(value: Any) -> bool: + return exact_in_flight_request(value) if exact_replacement else provable_posted_hosted_request(value) + stop_evidence_checked = False if ( bounded_replacement - and not any(provable_posted_hosted_request(value) for value in history) + and not any(permitted_in_flight_request(value) for value in history) and ( prior_taper_complete or any( @@ -5749,7 +5782,7 @@ def provable_posted_hosted_request(value: Any) -> bool: and target.pr == pr and target.status == policy.ReviewStatus.JUDGMENT_REQUIRED ): - if not fresh_taper: + if not fresh_taper and not exact_replacement: raise ControllerError( "bounded Hosted allocation after a judgment-required taper must explicitly reopen fresh taper" ) @@ -5769,12 +5802,12 @@ def provable_posted_hosted_request(value: Any) -> bool: bounded_replacement and target.pr == pr and target.status == policy.ReviewStatus.HELD - and any(provable_posted_hosted_request(value) for value in history) + and any(permitted_in_flight_request(value) for value in history) ): raise elif bounded_replacement: assert previous is not None - if previous.stop_basis is not None: + if previous.stop_basis is not None and not exact_replacement: raise ControllerError("a stopped allocation cannot be renewed") if self._head_repository_problem(item): raise ControllerError(f"PR #{pr} has an unsupported head repository") @@ -5798,10 +5831,12 @@ def provable_posted_hosted_request(value: Any) -> bool: _field(value, flag) is True for flag in ("held", "unstable", "rate_limited", "unreconciled", "parent_moved", "over_ceiling") ) and _field(value, "head", "reviewed_head") in (None, "", item.head) - if blocked and not provable_posted_hosted_request(value): + if blocked and not permitted_in_flight_request(value): raise ControllerError("current review evidence is blocked; allocation cannot be promised") baseline = tuple( - _field(value, "checkpoint", "checkpoint_id") for value in history if _field(value, "correction") is not True + _field(value, "checkpoint", "checkpoint_id") + for value in history + if _field(value, "correction") is not True and not exact_in_flight_request(value) ) if any(not isinstance(value, str) or not value for value in baseline): raise ControllerError("existing review evidence lacks a checkpoint identity") diff --git a/dev-tools/pr_review/sqlite_provider_imports.py b/dev-tools/pr_review/sqlite_provider_imports.py index b1c2e34a09..a9ecbed963 100644 --- a/dev-tools/pr_review/sqlite_provider_imports.py +++ b/dev-tools/pr_review/sqlite_provider_imports.py @@ -433,6 +433,8 @@ def _import_reply_only_hosted_checkpoint( checkpoint, state.response_id, state.duration_seconds, + repo, + pr_number, captured_head, record, hosted_payload, diff --git a/dev-tools/validation/test_pr_review_cli_runner.py b/dev-tools/validation/test_pr_review_cli_runner.py index 2a1c58e2c2..dd2390bf27 100644 --- a/dev-tools/validation/test_pr_review_cli_runner.py +++ b/dev-tools/validation/test_pr_review_cli_runner.py @@ -101,6 +101,29 @@ def test_minimum_and_maximum_are_optional_without_a_pinned_checkpoint(self): self.assertIsNone(maximum_only.min_additional_completed) self.assertEqual(maximum_only.max_additional_completed, 3) + def test_exact_additional_completed_accepts_only_a_positive_integer(self): + common = [ + "decide", + "allocation", + "grant", + "--pr", + "2827", + "--channel", + "cli", + "--head", + HEAD, + "--reason", + "three more completed CLI rounds", + "--exact-additional-completed", + ] + + args = _parser().parse_args([*common, "3"]) + + self.assertEqual(args.exact_additional_completed, 3) + for invalid in ("0", "-1", "not-an-integer"): + with self.subTest(invalid=invalid), self.assertRaises(SystemExit): + _parser().parse_args([*common, invalid]) + def test_legacy_cancel_shape_needs_no_cap_replacement(self): args = _parser().parse_args( [ diff --git a/dev-tools/validation/test_pr_review_controller.py b/dev-tools/validation/test_pr_review_controller.py index 414a305672..5f794ee432 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -3404,6 +3404,226 @@ def test_bounded_allocation_can_be_renewed_or_cancelled_explicitly(self): ) self.assertEqual(cancelled["allocations"], []) + def test_exact_allocation_maps_to_equal_bounds_and_replaces_a_stopped_allocation(self): + for channel in ("hosted", "cli"): + with self.subTest(channel=channel): + evidence = {(1, channel): [self.scope_timeline_evidence(channel=channel)]} + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + controller.decide_stop(pr=1, channel=channel, reason="human stopped ordinary discovery") + + renewed = controller.decide_allocation( + action="renew", + pr=1, + channel=channel, + head=HEAD_1, + exact_additional_completed=2, + reason="run exactly two more completed rounds", + ) + + self.assertEqual(renewed["allocation"]["min_additional_completed"], 2) + self.assertEqual(renewed["allocation"]["max_additional_completed"], 2) + self.assertIsNone(renewed["allocation"]["stop_basis"]) + self.assertFalse(renewed["allocation"].get("reopens_taper", False)) + + def test_exact_allocation_explicitly_replaces_an_exhausted_allocation(self): + evidence = {(1, "hosted"): [self.allocation_evidence(checkpoint="baseline")]} + controller = self.grant_bounded_allocation(checkpoint="baseline", cap=1, minimum=1, evidence=evidence) + evidence[(1, "hosted")].append(self.allocation_evidence(checkpoint="exhausted-result")) + self.assertEqual(controller.status()["prs"][0]["allocations"]["hosted"]["remaining"], 0) + + renewed = controller.decide_allocation( + action="renew", + pr=1, + channel="hosted", + head=HEAD_1, + exact_additional_completed=2, + reason="replace the exhausted tranche with exactly two more rounds", + ) + + self.assertEqual(renewed["progress"]["completed_count"], 0) + self.assertEqual(renewed["progress"]["remaining"], 2) + + def test_exact_allocation_retains_one_admitted_request_until_it_completes_or_fails(self): + for channel, terminal, same_checkpoint in ( + ("hosted", "completed", False), + ("cli", "completed", True), + ("cli", "failed", True), + ): + with self.subTest(channel=channel, terminal=terminal): + if channel == "hosted": + active = { + "pr": 1, + "head": HEAD_1, + "checkpoint": "trigger:45", + "trigger_id": 45, + "response_id": 46, + "state": "active", + "active_reservation": True, + "held": True, + "unstable": False, + "attributable": True, + "terminal": False, + "reason": HOSTED_ACTIVE_RESPONSE_REASON, + "anchor": { + "pr": 1, + "child_head": HEAD_1, + "parent_identity": "develop", + "parent_head": BASE, + "merge_base": BASE, + "patch_id": f"patch-{HEAD_1[:4]}", + }, + } + else: + active = { + "pr": 1, + "head": HEAD_1, + "child_head": HEAD_1, + "parent_identity": "develop", + "parent_head": BASE, + "merge_base": BASE, + "patch_id": f"patch-{HEAD_1[:4]}", + "checkpoint": "active-cli:run." + "a" * 32, + "active_review": True, + "held": True, + "current_lock_owner": True, + } + evidence = { + (1, channel): [ + self.scope_timeline_evidence(channel=channel), + active, + ] + } + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + controller.decide_stop(pr=1, channel=channel, reason="stop while the admitted request finishes") + + renewed = controller.decide_allocation( + action="renew", + pr=1, + channel=channel, + head=HEAD_1, + exact_additional_completed=2, + reason="retain the admitted request and complete exactly two rounds", + ) + self.assertEqual(renewed["progress"]["in_flight"], 1) + self.assertEqual(renewed["progress"]["used"], 0) + + if terminal == "completed": + replacement = self.allocation_evidence( + checkpoint=active["checkpoint"] if same_checkpoint else "completed-after-decision", + channel=channel, + ) + else: + replacement = self.allocation_evidence( + checkpoint=active["checkpoint"] if same_checkpoint else "failed-after-decision", + channel=channel, + completed=False, + attributable=False, + rate_limited=True, + ) + evidence[(1, channel)][1] = replacement + progress = controller.status()["prs"][0]["allocations"][channel] + + self.assertEqual(progress["used"], 1 if terminal == "completed" else 0) + self.assertEqual(progress["remaining"], 1 if terminal == "completed" else 2) + + def test_exact_allocation_rejects_unsupported_active_evidence_without_replacing_stop(self): + cases = { + "wrong-channel": {"channel": "hosted"}, + "wrong-pr": {"pr": 2}, + "moved-anchor": {"parent_head": HEAD_2}, + "ambiguous": {"unstable": True}, + } + for name, changed in cases.items(): + with self.subTest(name=name): + evidence = {(1, "cli"): [self.scope_timeline_evidence(channel="cli")]} + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + controller.decide_stop(pr=1, channel="cli", reason="retain the audited stop") + active = { + "pr": 1, + "head": HEAD_1, + "child_head": HEAD_1, + "parent_identity": "develop", + "parent_head": BASE, + "merge_base": BASE, + "patch_id": f"patch-{HEAD_1[:4]}", + "checkpoint": "active-cli:run." + "b" * 32, + "active_review": True, + "held": True, + "current_lock_owner": True, + **changed, + } + evidence[(1, "cli")].append(active) + stopped = controller.store.load() + + with self.assertRaises(ControllerError): + controller.decide_allocation( + action="renew", + pr=1, + channel="cli", + head=HEAD_1, + exact_additional_completed=2, + reason="unsupported active evidence must fail closed", + ) + + self.assertEqual(controller.store.load(), stopped) + + def test_exact_allocation_does_not_stop_at_existing_or_early_taper(self): + for channel, prior_count in (("hosted", 1), ("cli", 3)): + with self.subTest(channel=channel): + history = [ + self.allocation_evidence(checkpoint=f"prior-{index}", channel=channel) + for index in range(prior_count) + ] + history.append(self.scope_timeline_evidence(channel=channel)) + evidence = {(1, channel): history} + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + + controller.decide_allocation( + action="grant", + pr=1, + channel=channel, + head=HEAD_1, + exact_additional_completed=2, + reason="complete two rounds after ordinary taper", + ) + history.append(self.allocation_evidence(checkpoint="exact-first", channel=channel)) + first = controller.status()["prs"][0]["allocations"][channel] + self.assertEqual((first["status"], first["used"]), ("CAP_ACTIVE", 1)) + + history.append(self.allocation_evidence(checkpoint="exact-second", channel=channel)) + final = controller.status()["prs"][0]["allocations"][channel] + self.assertIn(final["status"], {"CAP_TAPERED", "CAP_AUDITED_STOP"}) + self.assertEqual((final["used"], final["remaining"]), (2, 0)) + + def test_exact_allocation_rejects_invalid_or_conflicting_values_without_mutation(self): + controller = self.make({1: pr(1, HEAD_1)}, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + original = controller.store.load() + + for exact, extra, message in ( + (0, {}, "positive integer"), + (-1, {}, "positive integer"), + (True, {}, "positive integer"), + (2, {"min_additional_completed": 1}, "cannot be combined"), + (2, {"max_additional_completed": 3}, "cannot be combined"), + (2, {"fresh_taper": True}, "preserve the existing taper"), + ): + with self.subTest(exact=exact, extra=extra), self.assertRaisesRegex(ControllerError, message): + controller.decide_allocation( + action="grant", + pr=1, + channel="hosted", + head=HEAD_1, + exact_additional_completed=exact, + reason="invalid exact allocation", + **extra, + ) + self.assertEqual(controller.store.load(), original) + def test_bounded_dry_result_can_be_renewed_without_stop_authorization(self): evidence = {(1, "hosted"): [self.allocation_evidence(checkpoint="baseline", channel="hosted")]} controller = self.grant_bounded_allocation( diff --git a/dev-tools/validation/test_pr_review_sqlite_provider_imports.py b/dev-tools/validation/test_pr_review_sqlite_provider_imports.py index 4d5ae00892..01b3c3e287 100644 --- a/dev-tools/validation/test_pr_review_sqlite_provider_imports.py +++ b/dev-tools/validation/test_pr_review_sqlite_provider_imports.py @@ -806,17 +806,24 @@ def test_reply_only_zero_checkpoint_requires_exact_edited_trigger_reply(self) -> path.parent.mkdir(parents=True) path.write_text(json.dumps(record), encoding="utf-8") - imported = pr_review.sqlite_provider_imports.import_hosted_checkpoint( - self.records, - repo=REPO, - pr_number=PR, - checkpoint=checkpoint, - actor="reviewer", - common=self.common, - scope="broad", - hosted_payload=payload, - ) + proof_method = pr_review.runtime.LiveEvidence._hosted_zero_reply_proof + with patch.object( + pr_review.runtime.LiveEvidence, + "_hosted_zero_reply_proof", + wraps=proof_method, + ) as zero_reply_proof: + imported = pr_review.sqlite_provider_imports.import_hosted_checkpoint( + self.records, + repo=REPO, + pr_number=PR, + checkpoint=checkpoint, + actor="reviewer", + common=self.common, + scope="broad", + hosted_payload=payload, + ) + self.assertEqual(zero_reply_proof.call_args.args[3:5], (REPO, PR)) self.assertEqual(imported["provider_id"], "trigger:101") self.assertEqual(imported["counts"], {"found": 0, "accepted": 0, "routed": 0}) self.assertEqual(set(imported["archive_artifacts"]), {"hosted_comments", "hosted_review", "metadata"}) From ec1937d109a4eaa29ba32f0e843b873273508025 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 04:28:55 +1300 Subject: [PATCH 03/10] fix(review): retain active Hosted allocation evidence --- dev-tools/pr_review/runtime.py | 3 ++ .../validation/test_pr_review_controller.py | 32 +++++++++++-------- 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/dev-tools/pr_review/runtime.py b/dev-tools/pr_review/runtime.py index 731730b2bf..1f96df1299 100644 --- a/dev-tools/pr_review/runtime.py +++ b/dev-tools/pr_review/runtime.py @@ -1684,6 +1684,9 @@ def _current_hosted_history( observation["anchor"] = dict(anchor) if isinstance(anchor, Mapping) else None observation["trigger_id"] = state.trigger_comment_id observation["response_id"] = state.response_id + observation["state"] = state.state + observation["attributable"] = state.attributed + observation["terminal"] = state.terminal if state.state == "ambiguous" and not operational_only: terminal_observation = self._terminal_ambiguous_hosted_observation(pr, record, state, payload) if terminal_observation is not None: diff --git a/dev-tools/validation/test_pr_review_controller.py b/dev-tools/validation/test_pr_review_controller.py index 5f794ee432..ed84bc8011 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -3452,19 +3452,7 @@ def test_exact_allocation_retains_one_admitted_request_until_it_completes_or_fai ): with self.subTest(channel=channel, terminal=terminal): if channel == "hosted": - active = { - "pr": 1, - "head": HEAD_1, - "checkpoint": "trigger:45", - "trigger_id": 45, - "response_id": 46, - "state": "active", - "active_reservation": True, - "held": True, - "unstable": False, - "attributable": True, - "terminal": False, - "reason": HOSTED_ACTIVE_RESPONSE_REASON, + record = { "anchor": { "pr": 1, "child_head": HEAD_1, @@ -3472,8 +3460,24 @@ def test_exact_allocation_retains_one_admitted_request_until_it_completes_or_fai "parent_head": BASE, "merge_base": BASE, "patch_id": f"patch-{HEAD_1[:4]}", - }, + } } + state = SimpleNamespace( + state="active", + head_sha=HEAD_1, + trigger_comment_id=45, + response_id=46, + terminal=False, + attributed=True, + reason=HOSTED_ACTIVE_RESPONSE_REASON, + ) + live_evidence = LiveEvidence("owner/repo", LiveGitHub("owner/repo")) + with ( + patch.object(hosted, "current_trigger_record_paths", return_value=[Path("/trigger.json")]), + patch.object(hosted, "load_trigger_reservation", return_value=record), + patch.object(hosted, "trigger_state", return_value=state), + ): + active = live_evidence._current_hosted_history(1, HEAD_1, {}, set())[0] else: active = { "pr": 1, From a52633675177bb7dd676f701765fedd187858708 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 09:52:12 +1300 Subject: [PATCH 04/10] Bind first Hosted archive capture and tighten allocation proof --- dev-tools/pr_review/cli.py | 18 +- dev-tools/pr_review/hosted.py | 117 +++++++++++-- dev-tools/pr_review/runtime.py | 3 + .../pr_review/sqlite_provider_imports.py | 1 + .../validation/test_pr_review_cli_runner.py | 27 +++ .../validation/test_pr_review_controller.py | 2 +- .../test_pr_review_evidence_hosted.py | 96 +++++++++-- .../test_pr_review_sqlite_hosted_capture.py | 157 ++++++++++++++++++ 8 files changed, 388 insertions(+), 33 deletions(-) diff --git a/dev-tools/pr_review/cli.py b/dev-tools/pr_review/cli.py index e801cb7eac..8c52b61cd4 100644 --- a/dev-tools/pr_review/cli.py +++ b/dev-tools/pr_review/cli.py @@ -39,6 +39,22 @@ class CliError(RuntimeError): pass +class _CliArgumentParser(argparse.ArgumentParser): + def parse_args(self, args=None, namespace=None): + parsed = super().parse_args(args, namespace) + if ( + getattr(parsed, "command", None) == "decide" + and getattr(parsed, "decide_command", None) == "allocation" + and getattr(parsed, "exact_additional_completed", None) is not None + and ( + getattr(parsed, "min_additional_completed", None) is not None + or getattr(parsed, "max_additional_completed", None) is not None + ) + ): + self.error("--exact-additional-completed cannot be combined with min or max additional-completed bounds") + return parsed + + def _positive_int(value: str) -> int: try: parsed = int(value) @@ -72,7 +88,7 @@ def _source_fix_sha(value: str) -> str: def _parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(prog="dev-tools/pr-review") + parser = _CliArgumentParser(prog="dev-tools/pr-review") parser.add_argument( "--acceptance-fixture", metavar="JSON", diff --git a/dev-tools/pr_review/hosted.py b/dev-tools/pr_review/hosted.py index 1ec845af8c..ae27b29126 100644 --- a/dev-tools/pr_review/hosted.py +++ b/dev-tools/pr_review/hosted.py @@ -1542,6 +1542,8 @@ def _archived_completed_thread_bodies( repo: str, pr_number: int, head: str, + response_id: int, + response_created_at: datetime, record: Mapping[str, Any] | None, current_record_path: str | Path | None, ) -> dict[int, tuple[str, str]]: @@ -1559,28 +1561,32 @@ def _archived_completed_thread_bodies( or type(trigger_id) is not int or trigger_id <= 0 or trigger_at is None + or type(response_id) is not int + or response_id <= 0 or not isinstance(record.get("head_sha"), str) or record["head_sha"].casefold() != head.casefold() ): return {} - selected_record = Path(current_record_path) if current_record_path is not None else default_trigger_record_path( - repo, pr_number - ) - if selected_record.is_symlink(): - return {} - common = _trigger_record_common_for_path(selected_record, repo, pr_number) - if common is None: - return {} - selected_state = state_path(common) - if selected_state.is_symlink() or not selected_state.is_dir(): - return {} - database = sqlite_state_path(selected_state) try: + selected_record = ( + Path(current_record_path) + if current_record_path is not None + else default_trigger_record_path(repo, pr_number) + ) + if selected_record.is_symlink(): + return {} + common = _trigger_record_common_for_path(selected_record, repo, pr_number) + if common is None: + return {} + selected_state = state_path(common) + if selected_state.is_symlink() or not selected_state.is_dir(): + return {} + database = sqlite_state_path(selected_state) database_stat = database.stat(follow_symlinks=False) - except FileNotFoundError: - return {} - if database.is_symlink() or not stat.S_ISREG(database_stat.st_mode): + if database.is_symlink() or not stat.S_ISREG(database_stat.st_mode): + return {} + except (OSError, TypeError, ValueError): return {} try: @@ -1589,16 +1595,82 @@ def _archived_completed_thread_bodies( attempt_history = records.attempt_history(pr_number) current_history = [item for item in attempt_history if item.get("attempt_id") == current_attempt_id] current_head = current_attempt.get("candidate_sha") + request_metadata = current_attempt.get("metadata") + current_row = current_history[0] if len(current_history) == 1 else None + current_started_at = parse_timestamp(current_attempt.get("started_at")) + current_state = current_attempt.get("state") + current_trigger_id = current_row.get("trigger_id") if current_row is not None else None + current_response_id = current_row.get("provider_review_id") if current_row is not None else None + current_finished_at = parse_timestamp(current_attempt.get("finished_at")) if ( current_attempt.get("source_pr") != pr_number or current_attempt.get("channel") != "hosted" or not isinstance(current_head, str) or current_head.casefold() != head.casefold() - or len(current_history) != 1 - or current_history[0].get("trigger_id") != str(trigger_id) + or not isinstance(request_metadata, dict) + or not isinstance(request_metadata.get("repository"), str) + or request_metadata["repository"].casefold() != repo.casefold() + or not isinstance(response_created_at, datetime) + or current_started_at is None + or current_started_at > trigger_at + or current_row is None + or current_row.get("state") != current_state + or current_row.get("started_at") != current_attempt.get("started_at") + or current_row.get("finished_at") != current_attempt.get("finished_at") ): return {} + if current_state == "started": + if ( + current_trigger_id not in (None, str(trigger_id)) + or current_response_id is not None + or current_finished_at is not None + ): + return {} + if records.attempt_artifacts(current_attempt_id): + return {} + elif current_state == "completed": + if ( + current_trigger_id != str(trigger_id) + or current_response_id != str(response_id) + or current_finished_at is None + or current_finished_at < response_created_at + or current_attempt.get("run_id") != current_attempt_id + ): + return {} + try: + current_artifacts = records.attempt_artifacts(current_attempt_id) + if not {"hosted_review", "hosted_comments", "metadata"} <= current_artifacts.keys(): + return {} + current_metadata = json.loads(current_artifacts["metadata"]) + except (TypeError, ValueError, json.JSONDecodeError): + return {} + current_observed_at = ( + parse_timestamp(current_metadata.get("observed_at")) if isinstance(current_metadata, dict) else None + ) + if ( + not isinstance(current_metadata, dict) + or current_metadata.get("state") != "completed" + or current_metadata.get("terminal") is not True + or current_metadata.get("attributable") is not True + or not isinstance(current_metadata.get("repository"), str) + or current_metadata["repository"].casefold() != repo.casefold() + or current_metadata.get("pull_request") != pr_number + or not isinstance(current_metadata.get("head_sha"), str) + or current_metadata["head_sha"].casefold() != head.casefold() + or type(current_metadata.get("trigger_id")) is not int + or str(current_metadata["trigger_id"]) != str(trigger_id) + or type(current_metadata.get("response_id")) is not int + or str(current_metadata["response_id"]) != str(response_id) + or current_observed_at is None + or current_observed_at != current_finished_at + ): + return {} + else: + # A terminal ambiguous or failed capture cannot be retroactively + # promoted by a later change in the public GitHub response. + return {} + candidates: dict[int, list[tuple[str, str]]] = {} for attempt in attempt_history: candidate_head = attempt.get("candidate_sha") @@ -1611,6 +1683,7 @@ def _archived_completed_thread_bodies( or not EXACT_SHA.fullmatch(candidate_head) or started_at is None or finished_at is None + or started_at > finished_at or finished_at >= trigger_at ): continue @@ -1685,6 +1758,7 @@ def _archived_completed_thread_bodies( review_submitted_at = parse_timestamp(matching_reviews[0].get("submittedAt")) if ( archived_trigger_at is None + or archived_trigger_at < started_at or archived_trigger_at > finished_at or review_submitted_at is None or review_submitted_at < archived_trigger_at @@ -1729,6 +1803,7 @@ def _addressed_thread_update_matches_archive( head: str, after: datetime, before: datetime | None, + response_id: int, archived_bodies: Mapping[int, tuple[str, str]], ) -> bool: """Accept only the exact known addressed footer appended to an archived finding.""" @@ -1752,6 +1827,8 @@ def _addressed_thread_update_matches_archive( or updated is None or updated <= after or (before is not None and updated >= before) + or type(response_id) is not int + or response_id <= 0 ): return False annotation = _ADDRESSED_COMMIT_ANNOTATION.search(body) @@ -2148,13 +2225,17 @@ def in_window(value: Any) -> bool | None: repo, pr_number, head, + response_id, + created, record, current_record_path, ) if isinstance(repo, str) and type(pr_number) is int and pr_number > 0 else {} ) - if _addressed_thread_update_matches_archive(item, head, after, before, archived_bodies): + if _addressed_thread_update_matches_archive( + item, head, after, before, response_id, archived_bodies + ): continue return False return True diff --git a/dev-tools/pr_review/runtime.py b/dev-tools/pr_review/runtime.py index 1f96df1299..7eb586e8d6 100644 --- a/dev-tools/pr_review/runtime.py +++ b/dev-tools/pr_review/runtime.py @@ -1116,6 +1116,7 @@ def _hosted_zero_reply_proof( captured_head: str, record: dict[str, Any], payload: dict[str, Any], + current_record_path: str | Path | None = None, ) -> dict[str, Any] | None: """Validate a finished-reply checkpoint when no PR review object exists. @@ -1190,6 +1191,7 @@ def _hosted_zero_reply_proof( response_id, next_trigger, record, + current_record_path, repo=repo, pr_number=pr_number, ) @@ -1243,6 +1245,7 @@ def _hosted_trigger_for_checkpoint( captured_head, record, payload, + path, ) or proof ) diff --git a/dev-tools/pr_review/sqlite_provider_imports.py b/dev-tools/pr_review/sqlite_provider_imports.py index a9ecbed963..74fad52672 100644 --- a/dev-tools/pr_review/sqlite_provider_imports.py +++ b/dev-tools/pr_review/sqlite_provider_imports.py @@ -438,6 +438,7 @@ def _import_reply_only_hosted_checkpoint( captured_head, record, hosted_payload, + path, ) if proof is None: raise ProviderImportError("Hosted reply has no exact trigger-window zero-finding proof") diff --git a/dev-tools/validation/test_pr_review_cli_runner.py b/dev-tools/validation/test_pr_review_cli_runner.py index dd2390bf27..886bb9cc6c 100644 --- a/dev-tools/validation/test_pr_review_cli_runner.py +++ b/dev-tools/validation/test_pr_review_cli_runner.py @@ -17,6 +17,7 @@ DEV_TOOLS = Path(__file__).resolve().parents[1] sys.path.insert(0, str(DEV_TOOLS)) +from pr_review import cli as cli_module from pr_review import cli_attempts, cli_runner, evidence, github, hosted from pr_review.cli import _parser, _render from pr_review.cli_runner import ( @@ -124,6 +125,32 @@ def test_exact_additional_completed_accepts_only_a_positive_integer(self): with self.subTest(invalid=invalid), self.assertRaises(SystemExit): _parser().parse_args([*common, invalid]) + def test_exact_additional_completed_rejects_min_or_max_before_dispatch(self): + common = [ + "decide", + "allocation", + "grant", + "--pr", + "2827", + "--channel", + "cli", + "--head", + HEAD, + "--reason", + "exact additional review count", + ] + self.assertEqual( + _parser().parse_args( + [*common, "--min-additional-completed", "1", "--max-additional-completed", "4"] + ).min_additional_completed, + 1, + ) + for bound in ("--min-additional-completed", "--max-additional-completed"): + with self.subTest(bound=bound), patch.object(cli_module, "_dispatch") as dispatch: + with self.assertRaises(SystemExit): + cli_module.main([*common, "--exact-additional-completed", "3", bound, "2"]) + dispatch.assert_not_called() + def test_legacy_cancel_shape_needs_no_cap_replacement(self): args = _parser().parse_args( [ diff --git a/dev-tools/validation/test_pr_review_controller.py b/dev-tools/validation/test_pr_review_controller.py index ed84bc8011..eb41ea956d 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -3600,7 +3600,7 @@ def test_exact_allocation_does_not_stop_at_existing_or_early_taper(self): history.append(self.allocation_evidence(checkpoint="exact-second", channel=channel)) final = controller.status()["prs"][0]["allocations"][channel] - self.assertIn(final["status"], {"CAP_TAPERED", "CAP_AUDITED_STOP"}) + self.assertEqual(final["status"], "CAP_TAPERED") self.assertEqual((final["used"], final["remaining"]), (2, 0)) def test_exact_allocation_rejects_invalid_or_conflicting_values_without_mutation(self): diff --git a/dev-tools/validation/test_pr_review_evidence_hosted.py b/dev-tools/validation/test_pr_review_evidence_hosted.py index 7b7c91d573..bb2a936ae2 100644 --- a/dev-tools/validation/test_pr_review_evidence_hosted.py +++ b/dev-tools/validation/test_pr_review_evidence_hosted.py @@ -17,7 +17,7 @@ sys.path.insert(0, str(ROOT / "dev-tools")) from pr_review import cli as cli_module -from pr_review import cli_attempts, evidence, github, hosted, sqlite_review_records +from pr_review import cli_attempts, evidence, github, hosted, runtime, sqlite_review_records from pr_review.cli_runner import ReviewResult from pr_review.sqlite_finding_text import _safe_finding_detail from pr_review.sqlite_provider_imports import _cli_detail, _cli_finding_title, _cli_headline @@ -168,18 +168,7 @@ def archived_addressed_reply_fixture(common: Path, *, include_baseline: bool = T channel="hosted", candidate_sha=HEAD, started_at="2026-09-23T00:01:50Z", - ) - records.finish_attempt( - "current-hosted-attempt", - state="ambiguous", - finished_at="2026-09-23T00:02:08Z", - trigger_id="10", - provider_review_id="11", - artifacts={ - "hosted_review": "[]", - "hosted_comments": json.dumps({"comments": []}), - "metadata": json.dumps({"state": "ambiguous"}), - }, + metadata={"repository": REPO}, ) trigger = comment(10, "owner", hosted.FULL_COMMAND, trigger_at) @@ -1891,6 +1880,16 @@ def test_finished_reply_with_empty_complete_history_is_clean_completion(self): def test_finished_reply_accepts_only_exact_archived_addressed_thread_updates(self): with tempfile.TemporaryDirectory() as directory: payload, record, record_path = archived_addressed_reply_fixture(Path(directory)) + common = hosted._trigger_record_common_for_path(record_path, REPO, PR) + self.assertIsNotNone(common) + database = common / "firemud" / "pr-review-stack.sqlite3" + records = SqliteReviewRecords(database) + current_attempt = records.attempt("current-hosted-attempt") + self.assertEqual(current_attempt["state"], "started") + current_row = next( + item for item in records.attempt_history(PR) if item["attempt_id"] == "current-hosted-attempt" + ) + self.assertIsNone(current_row["trigger_id"]) state = hosted.trigger_state(REPO, PR, payload, record, record_path) @@ -1898,6 +1897,77 @@ def test_finished_reply_accepts_only_exact_archived_addressed_thread_updates(sel self.assertTrue(state.attributed) self.assertEqual(state.response_id, 11) + def test_runtime_zero_reply_proof_uses_custom_trigger_record_database(self): + with tempfile.TemporaryDirectory() as directory: + payload, record, record_path = archived_addressed_reply_fixture(Path(directory)) + checkpoint = evidence.Checkpoint( + comment_id=40, + created_at="2026-09-23T00:03:00Z", + type="Hosted", + raw_found=0, + accepted=0, + reviewed_sha=HEAD, + file_count=1, + correction=False, + updated_at=None, + run_id=None, + hosted_review_id=11, + ) + + proof = runtime.LiveEvidence._hosted_zero_reply_proof( + checkpoint, + 11, + None, + REPO, + PR, + HEAD, + record, + payload, + record_path, + ) + + self.assertIsNotNone(proof) + self.assertEqual(proof["review_id"], 11) + + def test_finished_reply_fails_closed_on_archive_lookup_filesystem_error(self): + with tempfile.TemporaryDirectory() as directory: + payload, record, record_path = archived_addressed_reply_fixture(Path(directory)) + with patch.object(hosted, "state_path", side_effect=PermissionError("state directory inaccessible")): + state = hosted.trigger_state(REPO, PR, payload, record, record_path) + + self.assertEqual(state.state, "ambiguous") + self.assertFalse(state.attributed) + + def test_finished_reply_does_not_promote_ambiguous_or_mismatched_current_attempt(self): + cases = (("ambiguous", "10"), ("ambiguous", "99"), ("completed", "99")) + for attempt_state, trigger_id in cases: + with ( + self.subTest(state=attempt_state, trigger_id=trigger_id), + tempfile.TemporaryDirectory() as directory, + ): + payload, record, record_path = archived_addressed_reply_fixture(Path(directory)) + common = hosted._trigger_record_common_for_path(record_path, REPO, PR) + self.assertIsNotNone(common) + database = common / "firemud" / "pr-review-stack.sqlite3" + records = SqliteReviewRecords(database) + records.finish_attempt( + "current-hosted-attempt", + state=attempt_state, + finished_at="2026-09-23T00:02:08Z", + trigger_id=trigger_id, + provider_review_id="11", + artifacts={ + "hosted_review": "[]", + "hosted_comments": json.dumps({"comments": []}), + "metadata": json.dumps({"state": attempt_state}), + }, + ) + + state = hosted.trigger_state(REPO, PR, payload, record, record_path) + + self.assertEqual(state.state, "ambiguous") + self.assertFalse(state.attributed) + def test_finished_reply_keeps_unproven_or_changed_thread_output_ambiguous(self): cases = ( ("unknown baseline", False, None), diff --git a/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py b/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py index 684a54c4a1..5d76cf1ddf 100644 --- a/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py +++ b/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py @@ -1350,6 +1350,163 @@ def test_sync_backfills_missing_attempt_and_skips_linked_replay(self) -> None: self.assertTrue(replay["synced"], replay) self.assertTrue(replay["synced"][0]["idempotent_replay"]) + def test_sync_attributes_archived_addressed_thread_on_first_started_attempt_and_replays(self) -> None: + with tempfile.TemporaryDirectory() as directory: + common = Path(directory) / "git-common" + (common / "firemud" / "pr-review-stack.json").mkdir(parents=True) + records = self.new_records(common / "firemud" / "pr-review-stack.sqlite3") + old_head = "b" * 40 + old_attempt_id = "hosted-addressed-prior" + old_trigger_id = 801 + old_response_id = 802 + old_thread_comment_id = 803 + old_started_at = "2026-09-29T00:49:50Z" + old_trigger_at = "2026-09-29T00:50:00Z" + old_thread_created_at = "2026-09-29T00:50:30Z" + old_finished_at = "2026-09-29T00:51:00Z" + old_body = ( + "An archived CodeRabbit finding.\n\n" + "" + ) + old_review = { + "databaseId": old_response_id, + "author": {"login": "coderabbitai[bot]"}, + "body": "\nReviewing the archived candidate.", + "state": "COMMENTED", + "submittedAt": old_finished_at, + "commit": {"oid": old_head}, + } + old_trigger = self.trigger_comment( + trigger_id=old_trigger_id, + created_at=old_trigger_at, + ) + old_comments = { + "comments": [old_trigger], + "review_threads": [ + { + "comments": { + "nodes": [ + { + "databaseId": old_thread_comment_id, + "author": {"login": "coderabbitai[bot]"}, + "body": old_body, + "createdAt": old_thread_created_at, + "updatedAt": old_finished_at, + } + ] + } + } + ], + } + records.start_attempt( + attempt_id=old_attempt_id, + source_pr=PR, + channel="hosted", + candidate_sha=old_head, + started_at=old_started_at, + ) + records.finish_attempt( + old_attempt_id, + state="completed", + finished_at=old_finished_at, + trigger_id=str(old_trigger_id), + provider_review_id=str(old_response_id), + artifacts={ + "hosted_review": json.dumps([old_review]), + "hosted_comments": json.dumps(old_comments), + "metadata": json.dumps( + { + "state": "completed", + "terminal": True, + "attributable": True, + "repository": REPO, + "pull_request": PR, + "head_sha": old_head, + "trigger_id": old_trigger_id, + "response_id": old_response_id, + "observed_at": old_finished_at, + } + ), + }, + ) + + attempt_id = "hosted-sync-addressed-thread" + started_at = "2026-09-29T00:59:00Z" + trigger_at = "2026-09-29T01:00:00Z" + trigger = self.trigger_record( + trigger_id=901, + created_at=trigger_at, + posting_started_at=started_at, + attempt_id=attempt_id, + ) + record_path = self.write_trigger_record(common, trigger) + sqlite_hosted_capture.start_hosted_attempt( + records, + attempt_id=attempt_id, + source_pr=PR, + candidate_sha=HEAD, + started_at=started_at, + metadata={"repository": REPO}, + ) + summary = { + "databaseId": 903, + "author": {"login": "coderabbitai[bot]"}, + "body": ( + "No actionable comments were generated in the recent review.\n" + f"Reviewing files that changed from the base of the PR and between {old_head} and {HEAD}." + ), + "createdAt": "2026-09-29T00:59:30Z", + "updatedAt": "2026-09-29T01:02:00Z", + } + response = { + "databaseId": 902, + "author": {"login": "coderabbitai[bot]"}, + "body": "Full review finished.", + "createdAt": "2026-09-29T01:01:00Z", + "updatedAt": "2026-09-29T01:04:00Z", + "url": "https://github.example/owner/repo/pull/42#issuecomment-902", + } + addressed_thread_comment = { + "databaseId": old_thread_comment_id, + "author": {"login": "coderabbitai[bot]"}, + "body": f"{old_body}\n\nāœ… Addressed in commits {'c' * 7} to {HEAD[:7]}", + "createdAt": old_thread_created_at, + "updatedAt": "2026-09-29T01:03:00Z", + } + payload = self.payload( + comments=[self.trigger_comment(trigger_id=901, created_at=trigger_at), summary, response], + review_threads=[{"comments": {"nodes": [addressed_thread_comment]}}], + ) + + with patch.object(sqlite_hosted_capture.github, "fetch_pull_request", return_value=payload) as fetch: + first = sqlite_hosted_capture.sync_hosted_pending(records, REPO, common=common, pr_number=PR) + + fetch.assert_called_once_with(REPO, PR) + self.assertEqual(len(first["synced"]), 1, first) + self.assertEqual(first["synced"][0]["state"], "completed") + self.assertEqual(first["synced"][0]["counts"], {"found": 0, "accepted": 0, "routed": 0}) + self.assertEqual(records.attempt(attempt_id)["state"], "completed") + current_attempt = next( + item for item in records.attempt_history(PR) if item["attempt_id"] == attempt_id + ) + self.assertEqual(current_attempt["trigger_id"], "901") + self.assertEqual(current_attempt["provider_review_id"], "902") + self.assertEqual( + hosted.trigger_state(REPO, PR, payload, trigger, record_path).state, + "completed", + ) + + with patch.object( + sqlite_hosted_capture.github, + "fetch_pull_request", + side_effect=AssertionError("linked replay must not refetch GitHub"), + ) as replay_fetch: + replay = sqlite_hosted_capture.sync_hosted_pending(records, REPO, common=common, pr_number=PR) + + replay_fetch.assert_not_called() + self.assertEqual(len(replay["synced"]), 1, replay) + self.assertTrue(replay["synced"][0]["idempotent_replay"]) + def test_sync_keeps_active_pending_and_records_rate_limit(self) -> None: scenarios = ( ( From 1b7e694647a1d9baae7d0134299a0a4545e0580f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 10:05:57 +1300 Subject: [PATCH 05/10] Assert exact allocation active-evidence refusal --- dev-tools/validation/test_pr_review_controller.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/dev-tools/validation/test_pr_review_controller.py b/dev-tools/validation/test_pr_review_controller.py index eb41ea956d..01f2e1d8a6 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -3562,7 +3562,10 @@ def test_exact_allocation_rejects_unsupported_active_evidence_without_replacing_ evidence[(1, "cli")].append(active) stopped = controller.store.load() - with self.assertRaises(ControllerError): + with self.assertRaisesRegex( + ControllerError, + "current review evidence is blocked; allocation cannot be promised", + ): controller.decide_allocation( action="renew", pr=1, From 35a5486626c5246d4f5c07cecfb76aa3977b8636 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 11:29:52 +1300 Subject: [PATCH 06/10] fix: reserve verified posted Hosted requests in exact allocations --- design/developer-workflows/pr-lifecycle.md | 2 +- dev-tools/pr_review/controller.py | 47 ++++- dev-tools/pr_review/runtime.py | 3 +- .../validation/test_pr_review_controller.py | 184 ++++++++++++++++++ .../validation/test_pr_review_runtime.py | 42 ++++ 5 files changed, 270 insertions(+), 8 deletions(-) diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index 22b3009ac6..c97ad0c643 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -13,7 +13,7 @@ Use this guide for pull-request status, review handling, CI, Renovate, merging, - Hosted taper is one completed, attributable zero-useful result for that PR; CLI taper is three consecutive such results for that PR. Results count across reviewed heads without a lineage, patch-equivalence, or current-head requirement. Once reached, taper is durable: later commits, bases, patches, fixes, or reconciliation do not erase it or automatically reopen the channel. An explicit human `reopen` judgment or `allocation grant|renew --fresh-taper` starts a fresh per-PR/channel streak at its decision boundary; earlier dry results remain visible but cannot satisfy the new streak. An ordinary bounded allocation does not reset completed taper by itself. An accepted allocated result breaks the active streak; later taper is evaluated after that result. Accepted findings and fixes remain mandatory holds. Identity checks may guard a new request but never queue advancement past a PR whose channel is complete or human-stopped. Invalid, duplicate, already-fixed-only, and other completed zero-useful results count; a literal `0/0` is unnecessary. Policy overrides remain explicit and are never inferred automatically. - Future Hosted and CLI checkpoints report `found / accepted / routed`. `found` is the provider's raw count, `accepted` is a valid fix owned by the reviewed PR, and `routed` is an observation assigned to another owner without adjudicating it for that owner. Only accepted findings extend source taper or require an in-PR fix before its next review. A route is informational on its source PR and creates no source warning, taper hold, review-selection hold, or merge hold; the destination owner judges it independently. Existing public counts and captures remain unchanged, and old checkpoints have an unknown routed count rather than an inferred zero or retroactive reclassification. - For each PR, the controller derives the expected effective parent as the nearest preceding unmerged configured PR, or the repository default base after all predecessors merge. The request records the PR number, child head, expected parent identity and exact parent head, merge-base SHA, and unique patch identity. Without `--force`, admission requires the live base and parent tip to match that identity, the parent to be an ancestor of the candidate, and every earlier adjacent link to be coherent; `PARENT_MOVED` and `UNRECONCILED` remain holds even when a merge base exists. `--force` may acknowledge a known topology or merge-readiness warning only while the PR and committed candidate remain exact, and admission rechecks for identity movement. When the provider's actual diff base/ref differs from the expected parent, retain the provider-observed base/ref with the forced attempt; do not describe the expected queue parent as the diff that was reviewed. The warning remains relevant to merge readiness. -- Reconciliation or an unproven candidate may block a new request only while that channel's policy remains incomplete; `--force` can acknowledge a known reconciliation warning when PR and committed candidate identity are certain, but cannot override candidate uncertainty or undo completed taper or an explicit human stop. A Hosted/CLI head mismatch alone does not require another review or judgment. Further review after completion or a stop requires an explicit human `reopen` decision or fresh-taper allocation. +- Reconciliation or an unproven candidate may block a new request only while that channel's policy remains incomplete; `--force` can acknowledge a known reconciliation warning when PR and committed candidate identity are certain, but cannot override candidate uncertainty or undo completed taper or an explicit human stop. A Hosted/CLI head mismatch alone does not require another review or judgment. Further review after completion or a stop requires an explicit human `reopen` decision, fresh-taper allocation, or exact additional-completed allocation through `allocation grant|renew` as described below. - When a coherent rebase or retarget leaves historical evidence anchored to the old parent, record the exact transition with `dev-tools/pr-review decide reconcile --pr --channel hosted|cli --checkpoint --prior-head --reason ""`. This records the ancestry transition without erasing completed taper or granting new review credit. The controller verifies the old attributable anchor and current branch, parent, ancestry, merge-base, and patch identities for that transition; the decision becomes invalid after any bound identity changes. - When historical evidence is readable but lacks the modern linked anchor required by `decide reconcile`, use `dev-tools/pr-review decide transition --pr --head --reason ""` to record the observed legacy records without inventing new checkpoints or spending review quota. The exact observations captured by that transition become non-counting policy history and cannot satisfy taper, even if a legacy record appears completed and attributable; newer independently attributable results remain counting. Active Hosted reservations and unresolved findings remain separate request or merge obligations. - If that exact legacy transition is followed by a fresh review and a later coherent fix head, reauthorize only the same immutable fingerprints with `dev-tools/pr-review decide transition --reauthorize --pr --head --reason ""`. The controller requires a prior transition, verifies every carried record again, and requires every other observation to be normal completed attributable anchored evidence; newer evidence remains counting and subject to ordinary reconciliation and judgment. A changed head without this explicit reauthorization remains blocked, and the command never creates a checkpoint or consumes review quota. diff --git a/dev-tools/pr_review/controller.py b/dev-tools/pr_review/controller.py index 1ddfd072de..9ad2ce9a1d 100644 --- a/dev-tools/pr_review/controller.py +++ b/dev-tools/pr_review/controller.py @@ -5727,12 +5727,47 @@ def exact_in_flight_request(value: Any) -> bool: if not exact_replacement or _field(value, "channel") not in (None, selected.value): return False if selected == policy.Channel.HOSTED: - return self._hosted_active_response_overlaps_cli( - value, - pr, - item.head, - current, - require_response_identity=True, + if self._hosted_active_response_overlaps_cli( + value, pr, item.head, current, require_response_identity=True + ): + return True + trigger_id = _field(value, "trigger_id") + checkpoint = _field(value, "checkpoint", "checkpoint_id") + observed_head = _field(value, "head", "reviewed_head") + return ( + _field(value, "state") == "awaiting_response" + and _field(value, "posted") is True + and _field(value, "reason") == "no attributable terminal response" + and _field(value, "held") is True + and _field(value, "active_reservation") is True + and _field(value, "unstable") is not True + and _field(value, "attributable") is True + and _field(value, "terminal") is False + and _field(value, "response_id") is None + and type(_field(value, "pr")) is int + and _field(value, "pr") == pr + and type(trigger_id) is int + and trigger_id > 0 + and checkpoint == f"trigger:{trigger_id}" + and isinstance(observed_head, str) + and re.fullmatch(r"[0-9a-fA-F]{40}", observed_head) is not None + and observed_head.casefold() == item.head.casefold() + and not any( + _field(value, flag) is True + for flag in ( + "rate_limited", + "terminal_ambiguous", + "unreconciled", + "parent_moved", + "over_ceiling", + "provisional", + "correction", + "non_counting", + "completed", + "actionable", + ) + ) + and self._hosted_anchor_matches(value, pr, current) ) return self._active_cli_review_overlaps_hosted(value, pr, current) diff --git a/dev-tools/pr_review/runtime.py b/dev-tools/pr_review/runtime.py index 7eb586e8d6..fb3ef91934 100644 --- a/dev-tools/pr_review/runtime.py +++ b/dev-tools/pr_review/runtime.py @@ -1682,9 +1682,10 @@ def _current_hosted_history( "active_reservation": state.state in {"active", "awaiting_response"} or operational_only, "reason": state.reason, } - if state.state == "active": + if state.state in {"active", "awaiting_response"}: anchor = record.get("anchor") observation["anchor"] = dict(anchor) if isinstance(anchor, Mapping) else None + observation["posted"] = record.get("status") == "posted" observation["trigger_id"] = state.trigger_comment_id observation["response_id"] = state.response_id observation["state"] = state.state diff --git a/dev-tools/validation/test_pr_review_controller.py b/dev-tools/validation/test_pr_review_controller.py index 01f2e1d8a6..95d1d93e2d 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -1286,6 +1286,190 @@ def test_allocation_is_promised_before_review_and_does_not_make_pr_complete(self self.assertNotEqual(result["channels"]["hosted"], "COMPLETE") self.assertEqual(controller.resolve_hosted_target().snapshot.number, 1) + def test_exact_allocation_reserves_posted_awaiting_hosted_trigger_until_completion(self): + for action in ("grant", "renew"): + with self.subTest(action=action): + timeline = self.scope_timeline_evidence() + evidence = { + (1, "hosted"): [self.allocation_evidence(checkpoint="allocation-baseline"), timeline] + } + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) + controller.set_stack([1]) + if action == "renew": + controller.decide_allocation( + action="grant", + pr=1, + channel="hosted", + head=HEAD_1, + exact_additional_completed=2, + reason="initial two-result cap", + ) + + pending = { + "pr": 1, + "channel": "hosted", + "head": HEAD_1, + "checkpoint": "trigger:123", + "trigger_id": 123, + "response_id": None, + "state": "awaiting_response", + "posted": True, + "active_reservation": True, + "held": True, + "unstable": False, + "reason": "no attributable terminal response", + "attributable": True, + "terminal": False, + "anchor": hosted_anchor(), + } + evidence[(1, "hosted")].append(pending) + + result = controller.decide_allocation( + action=action, + pr=1, + channel="hosted", + head=HEAD_1, + exact_additional_completed=1, + reason="reserve the exact posted request already awaiting its response", + ) + + self.assertEqual(result["progress"]["used"], 0) + self.assertEqual(result["progress"]["in_flight"], 1) + self.assertNotIn("trigger:123", result["allocation"]["baseline_checkpoints"]) + + evidence[(1, "hosted")] = [ + timeline, + self.allocation_evidence( + checkpoint="5847200187", + channel="hosted", + raw=0, + ) + ] + completed = controller.status()["prs"][0]["allocations"]["hosted"] + self.assertEqual(completed["completed_count"], 1) + self.assertEqual(completed["in_flight"], 0) + + def test_exact_awaiting_hosted_allocation_does_not_consume_failures_or_rate_limits(self): + for label, terminal in ( + ("failure", {"completed": False, "attributable": False, "failed": True}), + ("rate limit", {"completed": False, "attributable": False, "rate_limited": True}), + ): + with self.subTest(result=label): + timeline = self.scope_timeline_evidence() + pending = { + "pr": 1, + "channel": "hosted", + "head": HEAD_1, + "checkpoint": "trigger:123", + "trigger_id": 123, + "response_id": None, + "state": "awaiting_response", + "posted": True, + "active_reservation": True, + "held": True, + "unstable": False, + "reason": "no attributable terminal response", + "attributable": True, + "terminal": False, + "anchor": hosted_anchor(), + } + evidence = {(1, "hosted"): [pending, timeline]} + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) + controller.set_stack([1]) + controller.decide_allocation( + action="grant", + pr=1, + channel="hosted", + head=HEAD_1, + exact_additional_completed=1, + reason="reserve one completion from the posted request", + ) + evidence[(1, "hosted")] = [ + timeline, + { + **self.allocation_evidence( + checkpoint="trigger:123", + channel="hosted", + anchored=False, + **terminal, + ), + "rate_limited": terminal.get("rate_limited", False), + } + ] + + progress = controller.status()["prs"][0]["allocations"]["hosted"] + + self.assertEqual(progress["completed_count"], 0) + self.assertEqual(progress["remaining"], 1) + + def test_exact_allocation_refuses_unsafe_or_ambiguous_awaiting_hosted_evidence(self): + valid = { + "pr": 1, + "channel": "hosted", + "head": HEAD_1, + "checkpoint": "trigger:123", + "trigger_id": 123, + "response_id": None, + "state": "awaiting_response", + "posted": True, + "active_reservation": True, + "held": True, + "unstable": False, + "reason": "no attributable terminal response", + "attributable": True, + "terminal": False, + "anchor": hosted_anchor(), + } + cases = ( + ("missing anchor", {key: value for key, value in valid.items() if key != "anchor"}), + ("unverified posted state", {**valid, "posted": False}), + ("mismatched anchor", {**valid, "anchor": {**hosted_anchor(), "patch_id": "other-patch"}}), + ("mismatched head", {**valid, "head": HEAD_2}), + ("malformed trigger ID", {**valid, "trigger_id": "123"}), + ("response already present", {**valid, "response_id": 124}), + ( + "pre-POST reservation", + { + **valid, + "checkpoint": "trigger:pending", + "trigger_id": None, + "state": "ambiguous", + "reason": "trigger posting boundary is not verified", + "attributable": False, + "unstable": True, + }, + ), + ( + "ambiguous response", + { + **valid, + "state": "ambiguous", + "reason": "response attribution is ambiguous", + "attributable": False, + "terminal": True, + "unstable": True, + }, + ), + ("rate-limited", {**valid, "rate_limited": True}), + ) + for label, observation in cases: + with self.subTest(evidence=label): + evidence = {(1, "hosted"): [observation]} + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) + controller.set_stack([1]) + + with self.assertRaises(ControllerError): + controller.decide_allocation( + action="grant", + pr=1, + channel="hosted", + head=HEAD_1, + exact_additional_completed=1, + reason="must refuse unsupported in-flight proof", + ) + + self.assertNotIn("1:hosted", controller._state().allocations) + def test_default_one_result_allocation_requeues_completed_taper_without_resetting_it(self): history = [ self.allocation_evidence( diff --git a/dev-tools/validation/test_pr_review_runtime.py b/dev-tools/validation/test_pr_review_runtime.py index 5bf701366a..52360d3d94 100644 --- a/dev-tools/validation/test_pr_review_runtime.py +++ b/dev-tools/validation/test_pr_review_runtime.py @@ -4552,6 +4552,48 @@ def test_active_hosted_observation_exposes_its_durable_anchor(self) -> None: self.assertEqual(observation["trigger_id"], 10) self.assertEqual(observation["response_id"], 11) + def test_posted_awaiting_hosted_observation_exposes_exact_trigger_and_durable_anchor(self) -> None: + now = datetime.now(timezone.utc).replace(microsecond=0) + trigger_at = (now - timedelta(minutes=1)).isoformat().replace("+00:00", "Z") + record = self._trigger_record(created=trigger_at) + state = SimpleNamespace( + trigger_comment_id=10, + response_id=None, + state="awaiting_response", + terminal=False, + attributed=True, + head_sha=HEAD, + reason="no attributable terminal response", + ) + payload = self._payload() + pull = payload["data"]["repository"]["pullRequest"] + pull.update({"number": 42, "baseRefName": "develop", "baseRefOid": BASE}) + snapshot = PullRequestSnapshot(42, "OPEN", "develop", BASE, HEAD, "feature", 1) + live = LiveGitHub("owner/repo") + with tempfile.TemporaryDirectory() as directory: + common = Path(directory) + record_path = hosted.default_trigger_record_path("owner/repo", 42, common) + record_path.parent.mkdir(parents=True) + record_path.write_text(json.dumps(record), encoding="utf-8") + with ( + patch.object(github, "fetch_pull_request", return_value=payload), + patch.object(live, "pull_request", return_value=snapshot), + patch.object(evidence, "git_common_dir", return_value=common), + patch.object(hosted, "trigger_state", return_value=state), + ): + history = list(LiveEvidence("owner/repo", live).history(42, "hosted")) + + observation = next(item for item in history if item.get("checkpoint") == "trigger:10") + self.assertEqual(observation["state"], "awaiting_response") + self.assertTrue(observation["posted"]) + self.assertTrue(observation["active_reservation"]) + self.assertTrue(observation["held"]) + self.assertTrue(observation["attributable"]) + self.assertFalse(observation["terminal"]) + self.assertEqual(observation["anchor"], record["anchor"]) + self.assertEqual(observation["trigger_id"], 10) + self.assertIsNone(observation["response_id"]) + def test_complete_audit_exposes_exact_active_hosted_response_identity(self) -> None: now = datetime.now(timezone.utc).replace(microsecond=0) trigger_at = (now - timedelta(minutes=2)).isoformat().replace("+00:00", "Z") From 3d101db687cfe7ea1be5e347366ee8b969c13028 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 11:40:58 +1300 Subject: [PATCH 07/10] test: name selected review-state directory explicitly --- dev-tools/validation/test_pr_review_evidence_hosted.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dev-tools/validation/test_pr_review_evidence_hosted.py b/dev-tools/validation/test_pr_review_evidence_hosted.py index bb2a936ae2..d497035170 100644 --- a/dev-tools/validation/test_pr_review_evidence_hosted.py +++ b/dev-tools/validation/test_pr_review_evidence_hosted.py @@ -137,8 +137,8 @@ def archived_addressed_reply_fixture(common: Path, *, include_baseline: bool = T "observed_at": old_finished_at, } - state_dir = common / "firemud" / "pr-review-stack.json" - state_dir.mkdir(parents=True) + selected_state = common / "firemud" / "pr-review-stack.json" + selected_state.mkdir(parents=True) database = common / "firemud" / "pr-review-stack.sqlite3" SqliteStateStore(database).update(lambda state: state) records = SqliteReviewRecords(database) From 6c551e61a0ef71c9413c7f8a3805e9a76b7fdbfd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 15:53:18 +1300 Subject: [PATCH 08/10] Clarify allocation recording and unsupported request evidence --- design/developer-workflows/pr-lifecycle.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index 615a559dd0..84a2ae809e 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -19,7 +19,7 @@ Use this guide for pull-request status, review handling, CI, Renovate, merging, - If that exact legacy transition is followed by a fresh review and a later coherent fix head, reauthorize only the same immutable fingerprints with `dev-tools/pr-review decide transition --reauthorize --pr --head --reason ""`. The controller requires a prior transition, verifies every carried record again, and requires every other observation to be normal completed attributable anchored evidence; newer evidence remains counting and subject to ordinary reconciliation and judgment. A changed head without this explicit reauthorization remains blocked, and the command never creates a checkpoint or consumes review quota. - A single previously audited Hosted fingerprint that is absent from the complete current history may be retired only with `--reauthorize --retire-missing-hosted-fingerprint `. This requires the exact prior fingerprint, coherent current topology, complete available Hosted trigger records and paginated GitHub review/comment history, terminal and uniquely attributable responses, no active or unresolved reservation, and no unresolved actionable findings; any missing or ambiguous proof remains held. The fingerprint stays in the transition audit and remains non-counting if it later reappears. This decision never reconstructs evidence or creates a checkpoint and does not grant review, taper, finding-count, or merge-readiness credit. - Record an explicit channel judgment with `dev-tools/pr-review decide judgment retain|reopen --pr --channel hosted|cli --head --checkpoint --reason ""`. Retain confirms the verified equivalent patch for request and queue safety; reopen explicitly requires fresh review without deleting historical completed taper and resets the taper streak at the bound checkpoint. For CLI, a reopen may bind the latest complete modern checkpoint to a proven descendant live head, but carries no new review credit until later completed results arrive. A narrow channel policy override uses `dev-tools/pr-review decide policy --pr --head --checkpoint --hosted-zero-useful --reason ""` or `--cli-zero-useful ` (exactly one channel); it sets that channel's zero-useful completion count for the exact checkpoint. -- Extend the existing allocation with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head [--checkpoint ] [--min-additional-completed ] [--max-additional-completed ] [--exact-additional-completed ] [--fresh-taper] --reason ""`. Both bounds count completed, attributable results for that PR and channel beginning at the decision; the optional checkpoint records the observed identity but does not move that count's start. With neither bound, the existing one-result promise remains (`min=1`, `max=1`). A minimum-only allocation has no maximum; a maximum-only allocation has no extra minimum (`min=0`). `--exact-additional-completed N` is mutually exclusive with the separate bounds and `--fresh-taper`, and records `min=max=N`, so ordinary taper cannot stop discovery before all `N` results and the cap stops discovery immediately afterward. It preserves the existing taper rather than starting a fresh streak. Use `allocation renew --exact-additional-completed N` to replace an existing allocation or audited human stop explicitly. A verifiable request already admitted at the exact-allocation decision remains in flight and counts only when it completes attributably; ambiguous or unsupported active evidence is refused. Without `--fresh-taper`, an allocation after completed taper affects queue eligibility and its additional-result count while preserving the existing historical taper display. Its zero-useful results continue the normal streak. An accepted allocated result resets the active streak at that result, while all earlier checkpoints remain visible with their original counts; after fixes, later zero-useful results can satisfy taper. `--fresh-taper` starts the active streak at the allocation decision immediately; earlier dry results remain visible historical evidence but cannot satisfy it. When both bounds are set, reject `min > max`; the minimum requires that many additional results even after fresh taper, while taper may stop earlier than the maximum once the minimum is met. Rate limits, connection failures, duplicates, partial or ambiguous responses, provisional captures, and other non-counting observations do not consume the count. Hosted and CLI allocations remain independent; request-time identity checks apply only when posting a new review. +- Extend the existing allocation with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head [--checkpoint ] [--min-additional-completed ] [--max-additional-completed ] [--exact-additional-completed ] [--fresh-taper] --reason ""`. Both bounds count completed, attributable results for that PR and channel beginning at the decision; the optional checkpoint records the observed identity but does not move that count's start. With neither bound, the existing one-result promise remains (`min=1`, `max=1`). A minimum-only allocation has no maximum; a maximum-only allocation has no extra minimum (`min=0`). `--exact-additional-completed N` is mutually exclusive with the separate bounds and `--fresh-taper`, and records `min=max=N`, so ordinary taper cannot stop discovery before all `N` results and the cap stops discovery immediately afterward. It preserves the existing taper rather than starting a fresh streak. Use `allocation renew --exact-additional-completed N` to replace an existing allocation or audited human stop explicitly. A verifiable request already admitted at the decision remains in flight and counts only when it completes attributably; pre-POST reservations, ambiguous evidence, failures, rate limits, and unsupported active evidence do not receive allocation credit. Recording an allowance does not clear request blockers: identity, exclusivity, finding, and attribution checks still apply at admission. Without `--fresh-taper`, an allocation after completed taper affects queue eligibility and its additional-result count while preserving the existing historical taper display. Its zero-useful results continue the normal streak. An accepted allocated result resets the active streak at that result, while all earlier checkpoints remain visible with their original counts; after fixes, later zero-useful results can satisfy taper. `--fresh-taper` starts the active streak at the allocation decision immediately; earlier dry results remain visible historical evidence but cannot satisfy it. When both bounds are set, reject `min > max`; the minimum requires that many additional results even after fresh taper, while taper may stop earlier than the maximum once the minimum is met. Rate limits, connection failures, duplicates, partial or ambiguous responses, provisional captures, and other non-counting observations do not consume the count. Hosted and CLI allocations remain independent; request-time identity checks apply only when posting a new review. - Normal taper can finish before a maximum once the minimum is met. After any additional result with accepted findings, no next request is allowed until those findings, current/outdated threads, actionable summary findings, and fix publication/validation obligations are clear, even if capacity remains. Once the maximum is used, no further request is allowed for that PR/channel; a maximum stop is not taper and does not waive accepted findings or fixes. `status` and `evidence` expose the minimum, maximum, completed count, baseline identity, in-flight results, taper state, and controlling reason. When the maximum is exhausted, the controller derives an audited human-cap stop and advances that channel through its normal selector without a separate `decide stop`, subject to the active-review safety described below. Pending obligations remain source-owned and visible as `cap exhausted; findings pending`; this stop is not taper, current-head review, CI/Smoke proof, or merge readiness. A bounded allocation can be replaced explicitly with `allocation renew` and new bounds; `allocation cancel` removes it. Ordinary fixes never reset its completed count. - When the Overseer deliberately allocates one further completed review before deciding whether to continue, record it before the review with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head --reason ""`. Completed-result counts belong to the PR and channel and survive later identity changes; rate limits, partial, duplicate, and unattributable results do not consume the allocation. Record a human decision to make no further requests with `dev-tools/pr-review decide stop --pr --channel hosted|cli --reason ""`. This audited PR/channel override bypasses the taper gate only for queue advancement; it is not taper completion or proof of review coverage, and it persists across head and parent changes. It requires no completed checkpoint, clean findings, idle provider, or coherent review topology. An already admitted CLI or Hosted run continues with its reservation, capture, attribution, and eventual findings intact; finishing that run does not clear the override. Stop recording and new-request admission share only the short state mutation boundary, while each provider keeps its execution exclusion. Optional `--head` and `--checkpoint` pins must match the observed identities; unavailable optional Git proof is recorded as absent, never fabricated. Existing ambiguity-retention and over-ceiling acknowledgment options record their specific evidence without granting review credit. Discovery can advance only when the same channel has no active provider run. Accepted fixes, pending captures and adjudication, attributable evidence, current and outdated threads, actionable summaries, required CI, runtime proof, ancestry, and merge safety remain independent obligations. A stop overrides taper only and does not manufacture a reviewed head or merge readiness. - For a channel that still needs review, targeting stops at the first held, unstable, unreconciled, over-ceiling, or judgment-blocked PR; it skips PRs whose channel has completed taper or an audited human stop. The narrow exception is a verified terminal, non-counting Hosted response: keep that PR incomplete and visible, but use the next coherent PR's Hosted window if one exists. Do not post another request on the ambiguous PR or grant it taper or merge credit; revisit its evidence or obtain an audited human stop before its merge handoff. Request-time identity and active-review checks still apply before any new request for an incomplete channel. A file-ceiling rejection requires a coherent topology decision; there is no normal incremental-review fallback. From 77baea38f5b9e18212dffaed4623294081a71ad0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:06:24 +1300 Subject: [PATCH 09/10] Verify pending Hosted identity before reserving allocation credit --- dev-tools/pr_review/controller.py | 108 ++++++++++++------ .../validation/test_pr_review_controller.py | 15 ++- 2 files changed, 85 insertions(+), 38 deletions(-) diff --git a/dev-tools/pr_review/controller.py b/dev-tools/pr_review/controller.py index 6e97b8c421..d6684acb47 100644 --- a/dev-tools/pr_review/controller.py +++ b/dev-tools/pr_review/controller.py @@ -1060,6 +1060,52 @@ def _hosted_active_response_overlaps_cli( and _field(observation, "terminal") is False ) + @staticmethod + def _hosted_awaiting_response_matches( + observation: Any, + expected_pr: int, + current_anchor: AnchorFacts | None, + ) -> bool: + """Verify a posted request awaiting acknowledgment without counting completion.""" + if current_anchor is None: + return False + trigger_id = _field(observation, "trigger_id") + observed_head = _field(observation, "head", "reviewed_head") + return ( + _field(observation, "state") == "awaiting_response" + and _field(observation, "posted") is True + and _field(observation, "reason") == "no attributable terminal response" + and _field(observation, "held") is True + and _field(observation, "active_reservation") is True + and _field(observation, "unstable") is not True + and _field(observation, "attributable") is True + and _field(observation, "terminal") is False + and _field(observation, "response_id") is None + and type(_field(observation, "pr")) is int + and _field(observation, "pr") == expected_pr + and type(trigger_id) is int + and trigger_id > 0 + and _field(observation, "checkpoint", "checkpoint_id") == f"trigger:{trigger_id}" + and isinstance(observed_head, str) + and observed_head.casefold() == current_anchor.child_head.casefold() + and not any( + _field(observation, flag) is True + for flag in ( + "rate_limited", + "terminal_ambiguous", + "unreconciled", + "parent_moved", + "over_ceiling", + "provisional", + "correction", + "non_counting", + "completed", + "actionable", + ) + ) + and ReviewController._hosted_anchor_matches(observation, expected_pr, current_anchor) + ) + @staticmethod def _active_cli_review_overlaps_hosted( observation: Any, @@ -3246,6 +3292,31 @@ def _bounded_allocation_evidence(allocation: ReviewAllocation, history: Sequence "in_flight": len(in_flight_ids), "error": "an in-flight review has an incomplete or changed stack anchor", } + if ( + allocation.channel == "hosted" + and ( + _field(value, "state") in {"awaiting_response", "ambiguous"} + or _field(value, "reason") == "no attributable terminal response" + ) + and not ReviewController._hosted_awaiting_response_matches( + value, + allocation.pr, + AnchorFacts( + allocation.pr, + active_head, + active_parent_identity, + active_parent_head, + active_merge_base, + active_patch_id, + ), + ) + ): + return { + "baseline": baseline, + "results": results, + "in_flight": len(in_flight_ids), + "error": "an awaiting Hosted request lacks verified posted identity", + } identity = _field(value, "trigger_id", "run_id", "reservation_id", "attempt_id") if identity is None and trigger_checkpoint is not None: identity = trigger_checkpoint.group(1) @@ -5805,42 +5876,7 @@ def admitted_in_flight_request(value: Any) -> bool: require_response_identity=True, ): return True - trigger_id = _field(value, "trigger_id") - observed_head = _field(value, "head", "reviewed_head") - return ( - _field(value, "state") == "awaiting_response" - and _field(value, "posted") is True - and _field(value, "reason") == "no attributable terminal response" - and _field(value, "held") is True - and _field(value, "active_reservation") is True - and _field(value, "unstable") is not True - and _field(value, "attributable") is True - and _field(value, "terminal") is False - and _field(value, "response_id") is None - and type(_field(value, "pr")) is int - and _field(value, "pr") == pr - and type(trigger_id) is int - and trigger_id > 0 - and _field(value, "checkpoint", "checkpoint_id") == f"trigger:{trigger_id}" - and isinstance(observed_head, str) - and observed_head.casefold() == request_anchor.child_head.casefold() - and not any( - _field(value, flag) is True - for flag in ( - "rate_limited", - "terminal_ambiguous", - "unreconciled", - "parent_moved", - "over_ceiling", - "provisional", - "correction", - "non_counting", - "completed", - "actionable", - ) - ) - and self._hosted_anchor_matches(value, pr, request_anchor) - ) + return self._hosted_awaiting_response_matches(value, pr, request_anchor) return self._active_cli_review_overlaps_hosted(value, pr, request_anchor) baseline = tuple( diff --git a/dev-tools/validation/test_pr_review_controller.py b/dev-tools/validation/test_pr_review_controller.py index 11ce8adef0..eea540d838 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -1532,7 +1532,8 @@ def test_exact_allocation_keeps_unsafe_or_ambiguous_awaiting_hosted_evidence_hel ) for label, observation in cases: with self.subTest(evidence=label): - evidence = {(1, "hosted"): [observation]} + timeline = self.scope_timeline_evidence() + evidence = {(1, "hosted"): [observation, timeline]} controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) controller.set_stack([1]) @@ -1547,7 +1548,17 @@ def test_exact_allocation_keeps_unsafe_or_ambiguous_awaiting_hosted_evidence_hel self.assertIn(observation["checkpoint"], result["allocation"]["baseline_checkpoints"]) self.assertEqual(result["progress"]["in_flight"], 0) - self.assertEqual(evidence[(1, "hosted")], [observation]) + snapshot = controller._bounded_allocation_evidence( + controller._state().allocations["1:hosted"], evidence[(1, "hosted")] + ) + self.assertEqual(snapshot["in_flight"], 0) + expected_error = ( + "an in-flight review has an incomplete or changed stack anchor" + if label in {"missing anchor", "incomplete anchor", "mismatched head"} + else "an awaiting Hosted request lacks verified posted identity" + ) + self.assertEqual(snapshot["error"], expected_error) + self.assertEqual(evidence[(1, "hosted")], [observation, timeline]) self.assertNotEqual(controller._target("hosted", expected_pr=1).status, ReviewStatus.READY) def test_default_one_result_allocation_requeues_completed_taper_without_resetting_it(self): From f86bab77dbd8364ccbb0d1961ee341249c48782a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:12:51 +1300 Subject: [PATCH 10/10] Recover exact unlinked Hosted completion from archived evidence --- dev-tools/pr_review/hosted.py | 2 +- .../test_pr_review_sqlite_hosted_capture.py | 65 ++++++++++++++++++- 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/dev-tools/pr_review/hosted.py b/dev-tools/pr_review/hosted.py index ae27b29126..de977a4d87 100644 --- a/dev-tools/pr_review/hosted.py +++ b/dev-tools/pr_review/hosted.py @@ -1635,7 +1635,7 @@ def _archived_completed_thread_bodies( or current_response_id != str(response_id) or current_finished_at is None or current_finished_at < response_created_at - or current_attempt.get("run_id") != current_attempt_id + or current_attempt.get("run_id") not in (None, current_attempt_id) ): return {} try: diff --git a/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py b/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py index 5d76cf1ddf..aff748d301 100644 --- a/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py +++ b/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py @@ -1351,6 +1351,12 @@ def test_sync_backfills_missing_attempt_and_skips_linked_replay(self) -> None: self.assertTrue(replay["synced"][0]["idempotent_replay"]) def test_sync_attributes_archived_addressed_thread_on_first_started_attempt_and_replays(self) -> None: + self._assert_sync_archived_addressed_thread_and_replay(partial_completed=False) + + def test_sync_recovers_unlinked_completed_addressed_thread_and_replays(self) -> None: + self._assert_sync_archived_addressed_thread_and_replay(partial_completed=True) + + def _assert_sync_archived_addressed_thread_and_replay(self, *, partial_completed: bool) -> None: with tempfile.TemporaryDirectory() as directory: common = Path(directory) / "git-common" (common / "firemud" / "pr-review-stack.json").mkdir(parents=True) @@ -1478,10 +1484,67 @@ def test_sync_attributes_archived_addressed_thread_on_first_started_attempt_and_ review_threads=[{"comments": {"nodes": [addressed_thread_comment]}}], ) + if partial_completed: + pull = payload["data"]["repository"]["pullRequest"] + finished_at = "2026-09-29T01:04:00Z" + records.finish_attempt( + attempt_id, + state="completed", + finished_at=finished_at, + trigger_id="901", + provider_review_id="902", + artifacts={ + "hosted_review": json.dumps([]), + "hosted_comments": json.dumps( + { + "comments": pull["comments"]["nodes"], + "review_threads": pull["reviewThreads"]["nodes"], + } + ), + "metadata": json.dumps( + { + "state": "completed", + "terminal": True, + "attributable": True, + "repository": REPO, + "pull_request": PR, + "head_sha": HEAD, + "trigger_id": 901, + "response_id": 902, + "observed_at": finished_at, + } + ), + }, + ) + self.assertIsNone(records.attempt(attempt_id)["run_id"]) + original_attempt = sqlite_review_records.SqliteReviewRecords.attempt + + def conflicting_run_link(store, selected_attempt_id): + attempt = original_attempt(store, selected_attempt_id) + if selected_attempt_id == attempt_id: + return {**attempt, "run_id": "conflicting-source-run"} + return attempt + + with patch.object( + sqlite_review_records.SqliteReviewRecords, "attempt", autospec=True, side_effect=conflicting_run_link + ): + self.assertEqual( + hosted.trigger_state(REPO, PR, payload, trigger, record_path).state, + "ambiguous", + ) + with patch.object(sqlite_hosted_capture.github, "fetch_pull_request", return_value=payload) as fetch: + if partial_completed: + fetch.side_effect = AssertionError("partial archive recovery must not fetch GitHub") first = sqlite_hosted_capture.sync_hosted_pending(records, REPO, common=common, pr_number=PR) - fetch.assert_called_once_with(REPO, PR) + if partial_completed: + fetch.assert_not_called() + self.assertEqual(first["errors"], []) + self.assertTrue(first["synced"][0]["recovered_from_archive"], first) + self.assertEqual(records.attempt(attempt_id)["run_id"], attempt_id) + else: + fetch.assert_called_once_with(REPO, PR) self.assertEqual(len(first["synced"]), 1, first) self.assertEqual(first["synced"][0]["state"], "completed") self.assertEqual(first["synced"][0]["counts"], {"found": 0, "accepted": 0, "routed": 0})