From 158e79e3984934d60adf2127a51ac89311bc1440 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 11:57:41 +1300 Subject: [PATCH 1/4] Separate exact human review allowances from request admission --- design/developer-workflows/pr-lifecycle.md | 4 +- dev-tools/pr_review/README.md | 2 + dev-tools/pr_review/cli.py | 7 + dev-tools/pr_review/controller.py | 157 +++++++-- dev-tools/pr_review/hosted.py | 260 +++++++++++++- dev-tools/pr_review/runtime.py | 16 +- .../pr_review/sqlite_provider_imports.py | 2 + dev-tools/pr_review/state.py | 15 +- .../validation/test_pr_review_cli_runner.py | 23 ++ .../validation/test_pr_review_controller.py | 322 ++++++++++++++++++ .../test_pr_review_evidence_hosted.py | 199 +++++++++++ .../test_pr_review_sqlite_provider_imports.py | 27 +- .../validation/test_pr_review_state_stack.py | 19 ++ 13 files changed, 1010 insertions(+), 43 deletions(-) diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index 726f860a62..65f4826763 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. @@ -31,6 +31,8 @@ Use this guide for pull-request status, review handling, CI, Renovate, merging, ## Review Orchestration +- Record human channel stops and exact additional completed-round allowances independently of stack reconciliation or request readiness. Preserve existing review history and taper; provider requests still require their own attribution, exclusivity, identity, and finding checks. A saved allowance does not clear a hold or retire an already admitted request. + - Configure merge order once with `dev-tools/pr-review stack set`; the controller owns automatic Hosted and CLI targeting across the configured coherent merge train, and each channel advances independently. A cooldown, failure, or CI hold in one lane does not idle the other lane or safe later work. Keep request-time gates and the Hosted publication boundary intact, allow at most one active Hosted request and one CLI process repository-wide, and re-run `status` after head, parent, base, or merge changes to expose `PARENT_MOVED` descendants. Reconcile before an ordinary request, or use `--force` only for a known warning with exact candidate identity and admission-time rechecks. - Exhausting an authorized maximum review allocation closes discovery for that PR and channel and advances that channel independently, even when accepted source fixes remain pending. Status retains `cap exhausted; findings pending` as source obligation information, with an audited human-cap stop rather than a discovery selection hold. Do not request another review on the capped source. An already admitted active review remains intact and prevents overlapping execution; its late findings remain source obligations. Minimum/maximum accounting, finding counts and resolutions remain unchanged. Cap closure is neither taper completion nor merge proof: accepted fixes, review threads, required CI and all merge-readiness requirements remain mandatory on the source PR. - Keep the train moving when one PR or channel is blocked: work on the next safe review or fix up the configured chain, including dependency-safe preparation ahead of the front. Do not stop at a blocked request, red CI, provider cooldown, or human merge wait while useful safe work remains. Report the concrete blocker and the work continuing elsewhere; stop only when no safe useful work remains or the human explicitly pauses the lane. diff --git a/dev-tools/pr_review/README.md b/dev-tools/pr_review/README.md index e15fdb9227..d138c31e4f 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. Recording this human allowance requires the configured PR, channel, exact live head, and reason, but does not require stack reconciliation, local Git anchor proof, runnable selection, or cleared findings. Available anchor facts are retained as audit context; unavailable Git facts remain null. Request admission still enforces attribution, exclusivity, identity warnings, and pending findings independently, so a saved allowance may remain held. 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..1ddb40a39b 100644 --- a/dev-tools/pr_review/controller.py +++ b/dev-tools/pr_review/controller.py @@ -966,7 +966,12 @@ def _hosted_anchor_matches( expected_pr: int, current_anchor: AnchorFacts | None, ) -> bool: - if current_anchor is None or current_anchor.pr != expected_pr: + if ( + current_anchor is None + or current_anchor.pr != expected_pr + or current_anchor.merge_base is None + or current_anchor.patch_id is None + ): return False anchor = _field(observation, "anchor") if not isinstance(anchor, Mapping) or type(anchor.get("pr")) is not int: @@ -1039,7 +1044,12 @@ def _active_cli_review_overlaps_hosted( expected_pr: int, current_anchor: AnchorFacts | None, ) -> bool: - if current_anchor is None or current_anchor.pr != expected_pr: + if ( + current_anchor is None + or current_anchor.pr != expected_pr + or current_anchor.merge_base is None + or current_anchor.patch_id is None + ): return False checkpoint = _field(observation, "checkpoint", "checkpoint_id") observed_head = _field(observation, "head", "reviewed_head") @@ -3432,12 +3442,31 @@ def result(status: str, reason: str, *, control: str, details: str | None = None details="the in-flight request does not count until it is complete and attributable", ) + # Earlier accepted findings remain obligations after a human allowance; + # recording a new baseline cannot turn them into request permission. + pending_baseline = next( + ( + value + for value in history + if _field(value, "checkpoint", "checkpoint_id") in allocation.baseline_checkpoints + and self._accepted_findings_pending(value, current.child_head if current else allocation.head) + ), + None, + ) + if pending_baseline is not None: + return result( + "CAP_EXHAUSTED_PENDING" if cap is not None and used >= cap else "CAP_FINDINGS_PENDING", + self._accepted_findings_pending_reason(pending_baseline), + control="unresolved_work", + ) + if any(completed["accepted"] > 0 for completed in snapshot["results"]): if current is None or reconciliation_result is None: cap_reached = cap is not None and used >= cap return result( "CAP_EXHAUSTED_PENDING" if cap_reached else "CAP_FINDINGS_PENDING", - "cap exhausted; findings pending" if cap_reached + "cap exhausted; findings pending" + if cap_reached else "accepted findings remain pending; current fix evidence is unavailable", control="unresolved_work", details="current fix evidence is unavailable" if cap_reached else None, @@ -3997,6 +4026,7 @@ def judgment_hold(reason: str) -> policy.ChannelDecision: allocation.head.casefold() == current.child_head.casefold() and allocation.parent_identity == current.parent_identity and allocation.parent_head.casefold() == current.parent_head.casefold() + and isinstance(allocation.merge_base, str) and allocation.merge_base.casefold() == current.merge_base.casefold() and allocation.patch_id == current.patch_id and reconciliation.status_for(pr) == stack.ReconciliationStatus.COHERENT @@ -5607,6 +5637,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 +5654,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) @@ -5661,8 +5708,22 @@ def decide_allocation( ) if action == "renew" and previous_is_bounded and not bounded_replacement: raise ControllerError("renewing a bounded allocation requires a new minimum or maximum") - live, reconciliation = self._reconciliation(state) - item = live[pr] + if exact_replacement: + # A human allowance is policy, not a request admission. Capture + # the actual PR identity without requiring stack or local Git proof. + item = _live(self._require_github().pull_request(pr), pr) + reconciliation = None + try: + merge_base = _sha(self.git.merge_base(item.base_tip, item.head), "merge base") + patch_id = self.git.patch_identity(merge_base, item.head) + if not isinstance(patch_id, str) or not patch_id.strip(): + raise ControllerError("Git provider returned an empty patch identity") + except (ControllerError, OSError, ValueError, subprocess.SubprocessError): + merge_base, patch_id = None, None + current = AnchorFacts(pr, item.head, item.base_ref, item.base_tip, merge_base, patch_id) + else: + live, reconciliation = self._reconciliation(state) + item = live[pr] if normalized_head != item.head: raise ControllerError("allocation head does not match the live pull-request head") if self._head_repository_problem(item): @@ -5682,16 +5743,20 @@ def update_allocation(current_state: ReviewState, replacement: ReviewAllocation updated = self.store.update(lambda current_state: update_allocation(current_state, None)) return {"action": action, "pr": pr, "channel": selected.value, "allocations": list(updated.allocations)} - if reconciliation.status_for(pr) in { - stack.ReconciliationStatus.UNRECONCILED, - stack.ReconciliationStatus.PARENT_MOVED, - }: - raise ControllerError("allocation requires a coherent current stack identity") - current = self._anchor(pr, item, reconciliation.links[pr]) + if not exact_replacement: + assert reconciliation is not None + if reconciliation.status_for(pr) in { + stack.ReconciliationStatus.UNRECONCILED, + stack.ReconciliationStatus.PARENT_MOVED, + }: + raise ControllerError("allocation requires a coherent current stack identity") + current = self._anchor(pr, item, reconciliation.links[pr]) history = _history(self._evidence_provider, pr, selected) - policy_history = self._policy_history(state, pr, selected, reconciliation) + policy_history = history if exact_replacement else self._policy_history(state, pr, selected, reconciliation) reopens_taper = fresh_taper - prior_taper_complete = policy.taper_satisfied_for_state(state, selected, policy_history) + prior_taper_complete = not exact_replacement and policy.taper_satisfied_for_state( + state, selected, policy_history + ) def provable_posted_hosted_request(value: Any) -> bool: trigger_id = _field(value, "trigger_id") @@ -5706,10 +5771,50 @@ 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 + # Counting retains the immutable identity captured at admission, + # even when the live head or parent has since moved. Execution + # still requires its separate current identity/admission checks. + captured = _field(value, "anchor") if selected == policy.Channel.HOSTED else value + request_anchor = AnchorFacts( + pr, + _field(captured, "child_head"), + _field(captured, "parent_identity"), + _field(captured, "parent_head"), + _field(captured, "merge_base"), + _field(captured, "patch_id"), + ) + if not ( + all( + isinstance(value, str) and re.fullmatch(r"[0-9a-fA-F]{40}", value) is not None + for value in (request_anchor.child_head, request_anchor.parent_head, request_anchor.merge_base) + ) + and isinstance(request_anchor.parent_identity, str) + and bool(request_anchor.parent_identity.strip()) + and isinstance(request_anchor.patch_id, str) + and bool(request_anchor.patch_id.strip()) + ): + return False + if selected == policy.Channel.HOSTED: + return self._hosted_active_response_overlaps_cli( + value, + pr, + request_anchor.child_head, + request_anchor, + require_response_identity=True, + ) + return self._active_cli_review_overlaps_hosted(value, pr, request_anchor) + + 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 exact_replacement + and not any(permitted_in_flight_request(value) for value in history) and ( prior_taper_complete or any( @@ -5734,7 +5839,7 @@ def provable_posted_hosted_request(value: Any) -> bool: allow_hosted_cli_overlap=selected == policy.Channel.HOSTED, ) stop_evidence_checked = True - if action == "grant": + if action == "grant" and not exact_replacement: target = self._target( selected, expected_pr=pr, @@ -5749,7 +5854,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,16 +5874,16 @@ 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: + elif bounded_replacement and not exact_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") - else: + elif not exact_replacement: assert previous is not None progress = self._allocation_progress( previous, @@ -5798,10 +5903,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 exact_replacement 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") @@ -5828,13 +5935,15 @@ def provable_posted_hosted_request(value: Any) -> bool: allocation, policy_history, current, - reconciliation.status_for(pr, selected.value), + reconciliation.status_for(pr, selected.value) + if reconciliation is not None + else stack.ReconciliationStatus.UNRECONCILED, state=state, reconciliation_result=reconciliation, stop_audit_cache={}, history_cache={}, ) - if progress["status"] == "INVALID": + if progress["status"] == "INVALID" and not exact_replacement: raise ControllerError(progress["reason"]) updated = self.store.update(lambda current_state: update_allocation(current_state, allocation)) result = { 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..1f96df1299 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, @@ -1673,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/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/pr_review/state.py b/dev-tools/pr_review/state.py index 343094f5db..215b00d5e7 100644 --- a/dev-tools/pr_review/state.py +++ b/dev-tools/pr_review/state.py @@ -697,9 +697,9 @@ def from_dict(cls, value: Mapping[str, Any]) -> LegacyEvidenceTransition: class ReviewAllocation: """A durable one-result allocation or explicit channel-stop decision. - The allocation is bound to the complete stack identity observed when an - operator made the promise. The controller may consume it only after a - completed result for that identity. New stop decisions record the exact + Ordinary allocations retain the complete observed stack identity. Exact + equal-bound human allowances may retain unavailable Git facts as null; + their request admission and attributable completion checks remain separate. New stop decisions record the exact optional reviewed checkpoint and available live audit context separately; legacy handoff fields remain readable for state migration and are never newly issued. """ @@ -739,15 +739,20 @@ def __post_init__(self) -> None: raise StateError("review allocation PR must be a positive integer") if self.channel not in {"hosted", "cli"}: raise StateError("review allocation channel must be hosted or cli") + exact_allowance = ( + type(self.min_additional_completed) is int + and self.min_additional_completed > 0 + and self.min_additional_completed == self.max_additional_completed + ) for name in ("head", "parent_head", "merge_base"): value = getattr(self, name) - if name == "merge_base" and value is None and self.stop_basis == "direct_human": + if name == "merge_base" and value is None and (self.stop_basis == "direct_human" or exact_allowance): continue if not isinstance(value, str) or not EXACT_SHA.fullmatch(value): raise StateError(f"review allocation {name} must be an exact SHA") for name in ("parent_identity", "patch_id", "reason"): value = getattr(self, name) - if name == "patch_id" and value is None and self.stop_basis == "direct_human": + if name == "patch_id" and value is None and (self.stop_basis == "direct_human" or exact_allowance): continue if not isinstance(value, str) or not value.strip(): raise StateError(f"review allocation {name} must be a non-empty string") 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..ae1f99dd78 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -3404,6 +3404,328 @@ 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": + record = { + "anchor": { + "pr": 1, + "child_head": HEAD_1, + "parent_identity": "develop", + "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, + "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_records_policy_without_clearing_unsupported_active_evidence(self): + cases = { + "wrong-channel": {"channel": "hosted"}, + "wrong-pr": {"pr": 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) + history_before = list(evidence[(1, "cli")]) + renewed = controller.decide_allocation( + action="renew", + pr=1, + channel="cli", + head=HEAD_1, + exact_additional_completed=2, + reason="record human allowance while unsafe provider evidence stays held", + ) + self.assertEqual(renewed["allocation"]["min_additional_completed"], 2) + self.assertIsNone(renewed["allocation"]["stop_basis"]) + self.assertIn(active["checkpoint"], renewed["allocation"]["baseline_checkpoints"]) + self.assertEqual(evidence[(1, "cli")], history_before) + self.assertNotEqual(controller._target("cli", expected_pr=1).status, ReviewStatus.READY) + + def test_exact_allocation_keeps_captured_stacked_in_flight_identity_without_git(self): + active = { + "pr": 1, + "head": HEAD_1, + "child_head": HEAD_1, + "parent_identity": "2", + "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, + } + history = [self.scope_timeline_evidence(channel="cli"), active] + controller = self.make({1: pr(1, HEAD_2, "feature-2", PARENT)}, {(1, "cli"): history}, sqlite=True) + controller.set_stack([1]) + with patch.object(controller.git, "merge_base", side_effect=ControllerError("unavailable Git")): + result = controller.decide_allocation( + action="grant", + pr=1, + channel="cli", + head=HEAD_2, + exact_additional_completed=2, + reason="preserve admitted request without stack proof", + ) + self.assertEqual(result["progress"]["in_flight"], 1) + self.assertNotIn(active["checkpoint"], result["allocation"]["baseline_checkpoints"]) + self.assertIsNone(result["allocation"]["merge_base"]) + history[1] = self.allocation_evidence(checkpoint=active["checkpoint"], channel="cli", parent_identity="2") + saved = controller.store.load().allocations["1:cli"] + self.assertEqual( + controller._bounded_allocation_evidence(saved, history)["results"][0]["checkpoint"], active["checkpoint"] + ) + + def test_exact_allocation_records_without_reconciliation_or_git_anchor(self): + for channel in ("hosted", "cli"): + for missing_anchor in (False, True): + with self.subTest(channel=channel, missing_anchor=missing_anchor): + history = [self.scope_timeline_evidence(channel=channel)] + controller = self.make( + {1: pr(1, HEAD_1)}, {(1, channel): history}, heads={"feature-1": HEAD_1}, sqlite=True + ) + controller.set_stack([1]) + with ( + patch.object(controller, "_reconciliation", side_effect=ControllerError("incoherent stack")), + patch.object(controller, "_target", side_effect=AssertionError("admission must stay separate")), + patch.object( + controller, + "_check_stop_evidence", + side_effect=AssertionError("stop audit must stay separate"), + ), + patch.object( + controller.git, + "merge_base", + side_effect=ControllerError("missing Git") if missing_anchor else None, + return_value=BASE, + ), + ): + result = controller.decide_allocation( + action="grant", + pr=1, + channel=channel, + head=HEAD_1, + exact_additional_completed=2, + reason="human allowance independent of topology", + ) + saved = controller.store.load().allocations[f"1:{channel}"] + self.assertEqual(saved.min_additional_completed, saved.max_additional_completed) + self.assertEqual(saved.max_additional_completed, 2) + self.assertEqual(saved.merge_base, None if missing_anchor else BASE) + self.assertEqual(result["progress"]["used"], 0) + self.assertEqual(history, [self.scope_timeline_evidence(channel=channel)]) + + def test_exact_allocation_preserves_pending_findings_without_stop_audit(self): + for channel in ("hosted", "cli"): + with self.subTest(channel=channel): + finding = self.allocation_evidence(checkpoint="pending", channel=channel, accepted=1) + history = [finding, self.scope_timeline_evidence(channel=channel)] + controller = self.make( + {1: pr(1, HEAD_1)}, {(1, channel): history}, heads={"feature-1": HEAD_1}, sqlite=True + ) + controller.set_stack([1]) + with patch.object( + controller, "_check_stop_evidence", side_effect=AssertionError("no stop prerequisite") + ): + result = controller.decide_allocation( + action="grant", + pr=1, + channel=channel, + head=HEAD_1, + exact_additional_completed=2, + reason="record allowance while finding remains open", + ) + self.assertIn("pending", result["allocation"]["baseline_checkpoints"]) + self.assertEqual(history[0], finding) + self.assertNotEqual(controller._target(channel, expected_pr=1).status, ReviewStatus.READY) + + 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_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") 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"}) diff --git a/dev-tools/validation/test_pr_review_state_stack.py b/dev-tools/validation/test_pr_review_state_stack.py index 97d38e7bb4..f02e03efbb 100644 --- a/dev-tools/validation/test_pr_review_state_stack.py +++ b/dev-tools/validation/test_pr_review_state_stack.py @@ -181,6 +181,25 @@ def test_review_allocation_accepts_decision_time_bounds_without_a_pinned_checkpo self.assertIsNone(restored.baseline_checkpoint) self.assertEqual(restored.min_additional_completed, 2) + def test_exact_equal_bound_allowance_roundtrips_unavailable_git_audit_facts(self): + allocation = ReviewAllocation( + pr=2827, + channel="cli", + head="a" * 40, + parent_identity="develop", + parent_head="b" * 40, + merge_base=None, + patch_id=None, + baseline_checkpoints=(), + reason="human requires exactly two more completed reviews", + min_additional_completed=2, + max_additional_completed=2, + ) + self.assertEqual(ReviewAllocation.from_dict(allocation.to_dict()), allocation) + for changed in ({"max_additional_completed": 3}, {"min_additional_completed": None}): + with self.subTest(changed=changed), self.assertRaises(StateError): + ReviewAllocation.from_dict({**allocation.to_dict(), **changed}) + def test_bounded_review_allocation_rejects_missing_baseline_or_invalid_cap(self): base = { "pr": 2827, From 5b5031d0c094ac129470f671dcad6dbbf35f363f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 12:09:29 +1300 Subject: [PATCH 2/4] Preserve selected trigger archive path in reply-only proof --- dev-tools/pr_review/runtime.py | 3 ++ .../pr_review/sqlite_provider_imports.py | 1 + .../test_pr_review_sqlite_provider_imports.py | 35 +++++++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/dev-tools/pr_review/runtime.py b/dev-tools/pr_review/runtime.py index 1f96df1299..aa8ef5369e 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=current_record_path, repo=repo, pr_number=pr_number, ) @@ -1243,6 +1245,7 @@ def _hosted_trigger_for_checkpoint( captured_head, record, payload, + current_record_path=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..d105fd9ffd 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, + current_record_path=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_sqlite_provider_imports.py b/dev-tools/validation/test_pr_review_sqlite_provider_imports.py index 01b3c3e287..ba3b36cecf 100644 --- a/dev-tools/validation/test_pr_review_sqlite_provider_imports.py +++ b/dev-tools/validation/test_pr_review_sqlite_provider_imports.py @@ -713,6 +713,40 @@ def test_explicit_modern_routed_counts_remain_strict_for_hosted_and_cli(self) -> scope="broad", ) + def test_reply_only_addressed_thread_import_uses_selected_archived_common_directory(self) -> None: + import test_pr_review_evidence_hosted as fixtures + + archived_common = self.common / "archived-common" + empty_default = self.common / "empty-default" + empty_default.mkdir() + payload, record, record_path = fixtures.archived_addressed_reply_fixture(archived_common) + payload["data"]["repository"]["pullRequest"]["number"] = fixtures.PR + record["anchor"] = { + "child_head": fixtures.HEAD, "parent_identity": "develop", + "parent_head": fixtures.BASE, "merge_base": fixtures.BASE, "patch_id": "archived-patch", + } + record_path.write_text(json.dumps(record), encoding="utf-8") + checkpoint_at = "2026-09-23T00:03:00Z" + body = (f"Hosted: 0 found / 0 accepted / 0 routed · {fixtures.HEAD[:12]} · 1 files\n" + "") + public_checkpoint = fixtures.comment(40, "owner", body, checkpoint_at) + payload["data"]["repository"]["pullRequest"]["comments"]["nodes"].append(public_checkpoint) + checkpoint = pr_review.evidence.parse_checkpoint_comments([{ + "id": 40, "body": body, "created_at": checkpoint_at, + "updated_at": checkpoint_at, "author_login": "owner", + }])[0][0] + with patch.object(pr_review.hosted, "_git_common_dir", return_value=empty_default): + imported = pr_review.sqlite_provider_imports.import_hosted_checkpoint( + self.records, repo=fixtures.REPO, pr_number=fixtures.PR, + checkpoint=checkpoint, actor="reviewer", common=archived_common, + scope="broad", hosted_payload=payload, + ) + self.assertEqual(imported["provider_id"], "trigger:10") + self.assertEqual(imported["counts"], {"found": 0, "accepted": 0, "routed": 0}) + self.assertEqual(list(empty_default.iterdir()), []) + archived = json.loads(imported["archive_artifacts"]["metadata"]) + self.assertEqual(archived["zero_reply_proof"]["commit_id"], fixtures.HEAD) + def test_reply_only_zero_checkpoint_requires_exact_edited_trigger_reply(self) -> None: trigger_at = "2026-09-27T11:40:00Z" response_created = "2026-09-27T11:50:00Z" @@ -824,6 +858,7 @@ def test_reply_only_zero_checkpoint_requires_exact_edited_trigger_reply(self) -> ) self.assertEqual(zero_reply_proof.call_args.args[3:5], (REPO, PR)) + self.assertEqual(zero_reply_proof.call_args.kwargs["current_record_path"], path) 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 69e3907977ade7c04efd4068604b18d676116c70 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 12:36:28 +1300 Subject: [PATCH 3/4] Separate human review policy from admission and recover verified late replies --- design/developer-workflows/pr-lifecycle.md | 2 +- dev-tools/pr_review/README.md | 4 +- dev-tools/pr_review/controller.py | 247 +++++----------- dev-tools/pr_review/sqlite_records_repair.py | 28 ++ dev-tools/pr_review/state.py | 15 +- .../validation/test_pr_review_controller.py | 267 +++++++++++------- .../test_pr_review_sqlite_records_repair.py | 102 +++++++ .../validation/test_pr_review_state_stack.py | 8 +- 8 files changed, 371 insertions(+), 302 deletions(-) diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index 65f4826763..9a8c3c4158 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -31,7 +31,7 @@ Use this guide for pull-request status, review handling, CI, Renovate, merging, ## Review Orchestration -- Record human channel stops and exact additional completed-round allowances independently of stack reconciliation or request readiness. Preserve existing review history and taper; provider requests still require their own attribution, exclusivity, identity, and finding checks. A saved allowance does not clear a hold or retire an already admitted request. +- Record human channel stops and review allocations independently of stack reconciliation or request readiness. Preserve existing review history and taper; provider requests still require their own attribution, exclusivity, identity, and finding checks. A saved allowance does not clear a hold or retire an already admitted request. - Configure merge order once with `dev-tools/pr-review stack set`; the controller owns automatic Hosted and CLI targeting across the configured coherent merge train, and each channel advances independently. A cooldown, failure, or CI hold in one lane does not idle the other lane or safe later work. Keep request-time gates and the Hosted publication boundary intact, allow at most one active Hosted request and one CLI process repository-wide, and re-run `status` after head, parent, base, or merge changes to expose `PARENT_MOVED` descendants. Reconcile before an ordinary request, or use `--force` only for a known warning with exact candidate identity and admission-time rechecks. - Exhausting an authorized maximum review allocation closes discovery for that PR and channel and advances that channel independently, even when accepted source fixes remain pending. Status retains `cap exhausted; findings pending` as source obligation information, with an audited human-cap stop rather than a discovery selection hold. Do not request another review on the capped source. An already admitted active review remains intact and prevents overlapping execution; its late findings remain source obligations. Minimum/maximum accounting, finding counts and resolutions remain unchanged. Cap closure is neither taper completion nor merge proof: accepted fixes, review threads, required CI and all merge-readiness requirements remain mandatory on the source PR. diff --git a/dev-tools/pr_review/README.md b/dev-tools/pr_review/README.md index d138c31e4f..4f53a85912 100644 --- a/dev-tools/pr_review/README.md +++ b/dev-tools/pr_review/README.md @@ -12,7 +12,7 @@ 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. Recording this human allowance requires the configured PR, channel, exact live head, and reason, but does not require stack reconciliation, local Git anchor proof, runnable selection, or cleared findings. Available anchor facts are retained as audit context; unavailable Git facts remain null. Request admission still enforces attribution, exclusivity, identity warnings, and pending findings independently, so a saved allowance may remain held. 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. +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. Recording any human allocation grant or renewal requires the configured PR, channel, exact live head, and reason, but does not require stack reconciliation, local Git anchor proof, runnable selection, or cleared findings. The same recording boundary applies to one-result and minimum/maximum allocations. Available anchor facts are retained as audit context; unavailable Git facts remain null. Request admission still enforces attribution, exclusivity, identity warnings, and pending findings independently, so a saved allowance may remain held. 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 @@ -55,7 +55,7 @@ Allocation finding-clearance audits distinguish an attributable terminal Hosted Hosted and CLI preflight briefly serialize on admission locks. A busy Hosted admission is retried through bounded fresh target selection; if contention persists, the command reports admission contention without treating the lock as proof of an active provider request. A lock refusal occurs before the Hosted reservation and POST. -For a historical or missed provider round, name its exact checkpoint comment. The repair command previews an isolated SQLite copy by default, validates the immutable provider identity and source decisions, and imports bounded/redacted source artifacts on `--apply`. Use `--all --continue-on-error` to report each checkpoint separately when some old evidence is incomplete. Missing historical evidence remains labelled; the command never invents an attributable review or changes taper. Repeat an exact import safely; conflicting evidence is refused. `records migrate` reports three distinct CLI capture outcomes while preserving run identity and source fingerprints: failed legacy captures become non-counting SQL attempts; a complete successful native capture is recovered as a completed source run only when it matches its existing started SQL attempt and proves one exact successful result; and an incomplete native capture matching its exact started SQL attempt is terminally classified as failed or timed out, with no source run or taper credit. Changed or conflicting evidence is reported instead of overwriting an earlier import. Normal history reads do not scan those files. +For a historical or missed provider round, name its exact checkpoint comment. The repair command previews an isolated SQLite copy by default, validates the immutable provider identity and source decisions, and imports bounded/redacted source artifacts on `--apply`. Use `--all --continue-on-error` to report each checkpoint separately when some old evidence is incomplete. Missing historical evidence remains labelled; the command never invents an attributable review or changes taper. Repeat an exact import safely; conflicting evidence is refused. A verified reply-only completion observed after an immutable ambiguous Hosted attempt can append its exact source run and checkpoint origin; the initial attempt and archived evidence remain unchanged. `records migrate` reports three distinct CLI capture outcomes while preserving run identity and source fingerprints: failed legacy captures become non-counting SQL attempts; a complete successful native capture is recovered as a completed source run only when it matches its existing started SQL attempt and proves one exact successful result; and an incomplete native capture matching its exact started SQL attempt is terminally classified as failed or timed out, with no source run or taper credit. Changed or conflicting evidence is reported instead of overwriting an earlier import. Normal history reads do not scan those files. ```sh dev-tools/pr-review records repair-provider \ diff --git a/dev-tools/pr_review/controller.py b/dev-tools/pr_review/controller.py index 1ddb40a39b..0f51007fa9 100644 --- a/dev-tools/pr_review/controller.py +++ b/dev-tools/pr_review/controller.py @@ -3442,6 +3442,43 @@ def result(status: str, reason: str, *, control: str, details: str | None = None details="the in-flight request does not count until it is complete and attributable", ) + # Exhausting the human maximum closes discovery independently of + # finding clearance or topology; those obligations stay visible. + if cap is not None and used >= cap: + if current is None or reconciliation_result is None or not latest: + return result( + "CAP_EXHAUSTED_PENDING", + "cap exhausted; findings pending", + control="unresolved_work", + details="complete current stack evidence is unavailable", + ) + try: + self._check_stop_evidence( + state, + allocation.pr, + policy.Channel(allocation.channel), + current, + reconciliation_result, + checkpoint_pin=latest["checkpoint"], + require_checkpoint_ancestry=False, + allow_cli_hosted_overlap=allocation.channel == policy.Channel.CLI.value, + allow_hosted_cli_overlap=allocation.channel == policy.Channel.HOSTED.value, + stop_audit_cache=stop_audit_cache, + history_cache=history_cache, + ) + except (ControllerError, ValueError) as error: + return result( + "CAP_EXHAUSTED_PENDING", + "cap exhausted; findings pending", + control="unresolved_work", + details=str(error), + ) + return result( + "CAP_AUDITED_STOP", + "the maximum additional completed reviews is reached and review obligations are clear", + control="maximum", + ) + # Earlier accepted findings remain obligations after a human allowance; # recording a new baseline cannot turn them into request permission. pending_baseline = next( @@ -3547,40 +3584,6 @@ def result(status: str, reason: str, *, control: str, details: str | None = None else "normal channel taper may finish before the maximum additional-review limit" ) return result("CAP_ACTIVE", reason, control="taper") - if current is None or reconciliation_result is None or not latest: - return result( - "CAP_EXHAUSTED_PENDING", - "cap exhausted; findings pending", - control="unresolved_work", - details="complete current stack evidence is unavailable", - ) - try: - self._check_stop_evidence( - state, - allocation.pr, - policy.Channel(allocation.channel), - current, - reconciliation_result, - checkpoint_pin=latest["checkpoint"], - require_checkpoint_ancestry=False, - allow_cli_hosted_overlap=allocation.channel == policy.Channel.CLI.value, - allow_hosted_cli_overlap=allocation.channel == policy.Channel.HOSTED.value, - stop_audit_cache=stop_audit_cache, - history_cache=history_cache, - ) - except (ControllerError, ValueError) as error: - return result( - "CAP_EXHAUSTED_PENDING", - "cap exhausted; findings pending", - control="unresolved_work", - details=str(error), - ) - return result( - "CAP_AUDITED_STOP", - "the maximum additional completed reviews is reached and review obligations are clear", - control="maximum", - ) - def _allocation_progress( self, allocation: ReviewAllocation, @@ -3655,6 +3658,12 @@ def result( ) baseline = set(allocation.baseline_checkpoints) + pending_baseline = next( + (value for value in history + if _field(value, "checkpoint", "checkpoint_id") in baseline + and self._accepted_findings_pending(value, current.child_head if current else allocation.head)), + None, + ) subsequent = [ item for item in history @@ -3701,6 +3710,8 @@ def result( checkpoint, ) if not matching: + if pending_baseline is not None: + return result("CAP_FINDINGS_PENDING", self._accepted_findings_pending_reason(pending_baseline)) return result("PROMISED", "waiting for one completed attributable review of this PR and channel") review = matching[0] @@ -3708,6 +3719,8 @@ def result( accepted = _field(review, "accepted") if type(accepted) is not int or accepted < 0: return result("INVALID", "completed review has an invalid accepted-finding count") + if pending_baseline is not None: + return result("EXHAUSTED_PENDING", self._accepted_findings_pending_reason(pending_baseline), checkpoint, accepted) if current is None: return result("EXHAUSTED_PENDING", "current finding and fix evidence is unavailable", checkpoint, accepted) if any( @@ -5708,22 +5721,17 @@ def decide_allocation( ) if action == "renew" and previous_is_bounded and not bounded_replacement: raise ControllerError("renewing a bounded allocation requires a new minimum or maximum") - if exact_replacement: - # A human allowance is policy, not a request admission. Capture - # the actual PR identity without requiring stack or local Git proof. - item = _live(self._require_github().pull_request(pr), pr) - reconciliation = None - try: - merge_base = _sha(self.git.merge_base(item.base_tip, item.head), "merge base") - patch_id = self.git.patch_identity(merge_base, item.head) - if not isinstance(patch_id, str) or not patch_id.strip(): - raise ControllerError("Git provider returned an empty patch identity") - except (ControllerError, OSError, ValueError, subprocess.SubprocessError): - merge_base, patch_id = None, None - current = AnchorFacts(pr, item.head, item.base_ref, item.base_tip, merge_base, patch_id) - else: - live, reconciliation = self._reconciliation(state) - item = live[pr] + # Human allowance recording is policy, not request admission. Capture + # the actual PR identity without requiring stack or local Git proof. + item = _live(self._require_github().pull_request(pr), pr) + try: + merge_base = _sha(self.git.merge_base(item.base_tip, item.head), "merge base") + patch_id = self.git.patch_identity(merge_base, item.head) + if not isinstance(patch_id, str) or not patch_id.strip(): + raise ControllerError("Git provider returned an empty patch identity") + except (ControllerError, OSError, ValueError, subprocess.SubprocessError): + merge_base, patch_id = None, None + current = AnchorFacts(pr, item.head, item.base_ref, item.base_tip, merge_base, patch_id) if normalized_head != item.head: raise ControllerError("allocation head does not match the live pull-request head") if self._head_repository_problem(item): @@ -5743,36 +5751,11 @@ def update_allocation(current_state: ReviewState, replacement: ReviewAllocation updated = self.store.update(lambda current_state: update_allocation(current_state, None)) return {"action": action, "pr": pr, "channel": selected.value, "allocations": list(updated.allocations)} - if not exact_replacement: - assert reconciliation is not None - if reconciliation.status_for(pr) in { - stack.ReconciliationStatus.UNRECONCILED, - stack.ReconciliationStatus.PARENT_MOVED, - }: - raise ControllerError("allocation requires a coherent current stack identity") - current = self._anchor(pr, item, reconciliation.links[pr]) history = _history(self._evidence_provider, pr, selected) - policy_history = history if exact_replacement else self._policy_history(state, pr, selected, reconciliation) reopens_taper = fresh_taper - prior_taper_complete = not exact_replacement and policy.taper_satisfied_for_state( - state, selected, policy_history - ) - - def provable_posted_hosted_request(value: Any) -> bool: - trigger_id = _field(value, "trigger_id") - return ( - bounded_replacement - and selected == policy.Channel.HOSTED - and _field(value, "reason") == HOSTED_ACTIVE_RESPONSE_REASON - and _field(value, "held") is True - and type(trigger_id) is int - and trigger_id > 0 - and _field(value, "checkpoint") == f"trigger:{trigger_id}" - 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): + def admitted_in_flight_request(value: Any) -> bool: + if _field(value, "channel") not in (None, selected.value): return False # Counting retains the immutable identity captured at admission, # even when the live head or parent has since moved. Execution @@ -5807,108 +5790,10 @@ def exact_in_flight_request(value: Any) -> bool: ) return self._active_cli_review_overlaps_hosted(value, pr, request_anchor) - 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 exact_replacement - and not any(permitted_in_flight_request(value) for value in history) - and ( - prior_taper_complete - or any( - _field(value, "completed") is True - and _field(value, "attributable") is True - and _field(value, "provisional") is not True - and type(_field(value, "accepted")) is int - and _field(value, "accepted") > 0 - for value in policy_history - ) - ) - ): - self._check_stop_evidence( - state, - pr, - selected, - current, - reconciliation, - checkpoint_pin=None, - require_checkpoint_ancestry=False, - allow_cli_hosted_overlap=selected == policy.Channel.CLI, - allow_hosted_cli_overlap=selected == policy.Channel.HOSTED, - ) - stop_evidence_checked = True - if action == "grant" and not exact_replacement: - target = self._target( - selected, - expected_pr=pr, - allow_completed_allocation=True, - ) - try: - self._ensure_runnable(target, require_force_for_warnings=True) - except ControllerError: - if ( - bounded_replacement - and selected == policy.Channel.HOSTED - and target.pr == pr - and target.status == policy.ReviewStatus.JUDGMENT_REQUIRED - ): - if not fresh_taper and not exact_replacement: - raise ControllerError( - "bounded Hosted allocation after a judgment-required taper must explicitly reopen fresh taper" - ) - if not stop_evidence_checked: - self._check_stop_evidence( - state, - pr, - selected, - current, - reconciliation, - checkpoint_pin=None, - require_checkpoint_ancestry=not fresh_taper, - allow_cli_hosted_overlap=selected == policy.Channel.CLI, - allow_hosted_cli_overlap=selected == policy.Channel.HOSTED, - ) - elif not ( - bounded_replacement - and target.pr == pr - and target.status == policy.ReviewStatus.HELD - and any(permitted_in_flight_request(value) for value in history) - ): - raise - elif bounded_replacement and not exact_replacement: - assert previous 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") - elif not exact_replacement: - assert previous is not None - progress = self._allocation_progress( - previous, - history, - current, - reconciliation.status_for(pr, selected.value), - state=state, - reconciliation_result=reconciliation, - ) - if ( - progress["status"] in {"EXHAUSTED_PENDING", "HANDED_OFF", "STOPPED"} - or progress["checkpoint"] is not None - ): - raise ControllerError("consumed or stopped review allocations cannot be renewed") - for value in history: - blocked = any( - _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 exact_replacement 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 and not exact_in_flight_request(value) + if _field(value, "correction") is not True and not admitted_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") @@ -5933,18 +5818,14 @@ def permitted_in_flight_request(value: Any) -> bool: if bounded_replacement: progress = self._bounded_allocation_progress( allocation, - policy_history, + history, current, - reconciliation.status_for(pr, selected.value) - if reconciliation is not None - else stack.ReconciliationStatus.UNRECONCILED, + stack.ReconciliationStatus.UNRECONCILED, state=state, - reconciliation_result=reconciliation, + reconciliation_result=None, stop_audit_cache={}, history_cache={}, ) - if progress["status"] == "INVALID" and not exact_replacement: - raise ControllerError(progress["reason"]) updated = self.store.update(lambda current_state: update_allocation(current_state, allocation)) result = { "action": action, diff --git a/dev-tools/pr_review/sqlite_records_repair.py b/dev-tools/pr_review/sqlite_records_repair.py index f6bf81b654..192cb06e83 100644 --- a/dev-tools/pr_review/sqlite_records_repair.py +++ b/dev-tools/pr_review/sqlite_records_repair.py @@ -220,6 +220,34 @@ def import_checkpoint(target: SqliteReviewRecords) -> dict[str, Any]: ) if matching_attempts: attempt = matching_attempts[0] + if checkpoint.type == "Hosted" and attempt["state"] == "ambiguous" and attempt["run_id"] is None: + # A reply may be edited to completion after the first immutable + # observation. Retain that observation and append only the + # canonical, independently verified reply-only source import. + with tempfile.TemporaryDirectory(prefix="pr-review-late-reply-") as scratch: + probe = _clone_records(records, Path(scratch) / "records.sqlite3") + verified = import_checkpoint(probe) + metadata = json.loads(verified.get("archive_artifacts", {}).get("metadata", "{}")) + trigger = metadata.get("trigger_record", {}) + attempt_repo = records.attempt(attempt["attempt_id"])["metadata"].get("repository") + proof = metadata.get("zero_reply_proof", {}) + if ( + metadata.get("capture_format") != "firemud-hosted-trigger-reply/v1" + or metadata.get("repository") != repo.casefold() + or not isinstance(attempt_repo, str) + or attempt_repo.casefold() != repo.casefold() + or metadata.get("pull_request") != pr_number + or trigger.get("head_sha") != attempt["candidate_sha"] + or proof.get("commit_id") != attempt["candidate_sha"] + or str(metadata.get("trigger_id")) != attempt["trigger_id"] + or str(metadata.get("response_id")) != attempt["provider_review_id"] + or trigger.get("sqlite_attempt_id") != attempt["attempt_id"] + or attempt["checkpoint_id"] not in (None, str(checkpoint.comment_id)) + or verified.get("counts") != {"found": 0, "accepted": 0, "routed": 0} + ): + raise SqliteRecordsRepairError("late Hosted reply conflicts with its immutable ambiguous attempt") + imported = import_checkpoint(records) + return imported, _provider_id(checkpoint, imported) if attempt["state"] != "completed" or attempt["run_id"] != attempt["attempt_id"]: raise SqliteRecordsRepairError( "matching provider attempt is not linked to its exact completed source run" diff --git a/dev-tools/pr_review/state.py b/dev-tools/pr_review/state.py index 215b00d5e7..96991e9038 100644 --- a/dev-tools/pr_review/state.py +++ b/dev-tools/pr_review/state.py @@ -697,9 +697,9 @@ def from_dict(cls, value: Mapping[str, Any]) -> LegacyEvidenceTransition: class ReviewAllocation: """A durable one-result allocation or explicit channel-stop decision. - Ordinary allocations retain the complete observed stack identity. Exact - equal-bound human allowances may retain unavailable Git facts as null; - their request admission and attributable completion checks remain separate. New stop decisions record the exact + Human allowances retain available observed identity facts; unavailable + Git facts remain null. Request admission and attributable completion + checks remain separate from recording the human policy. New stop decisions record the exact optional reviewed checkpoint and available live audit context separately; legacy handoff fields remain readable for state migration and are never newly issued. """ @@ -739,20 +739,15 @@ def __post_init__(self) -> None: raise StateError("review allocation PR must be a positive integer") if self.channel not in {"hosted", "cli"}: raise StateError("review allocation channel must be hosted or cli") - exact_allowance = ( - type(self.min_additional_completed) is int - and self.min_additional_completed > 0 - and self.min_additional_completed == self.max_additional_completed - ) for name in ("head", "parent_head", "merge_base"): value = getattr(self, name) - if name == "merge_base" and value is None and (self.stop_basis == "direct_human" or exact_allowance): + if name == "merge_base" and value is None: continue if not isinstance(value, str) or not EXACT_SHA.fullmatch(value): raise StateError(f"review allocation {name} must be an exact SHA") for name in ("parent_identity", "patch_id", "reason"): value = getattr(self, name) - if name == "patch_id" and value is None and (self.stop_basis == "direct_human" or exact_allowance): + if name == "patch_id" and value is None: continue if not isinstance(value, str) or not value.strip(): raise StateError(f"review allocation {name} must be a non-empty string") diff --git a/dev-tools/validation/test_pr_review_controller.py b/dev-tools/validation/test_pr_review_controller.py index ae1f99dd78..28b714359f 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -360,7 +360,7 @@ def test_allocation_counts_survive_head_parent_and_merge_base_movement(self): self.assertEqual(progress["max_additional_completed"], count) if bounded: self.assertTrue(progress["taper_complete"]) - self.assertEqual(progress["status"], "CAP_TAPERED") + self.assertEqual(progress["status"], "CAP_AUDITED_STOP") else: self.assertEqual(progress["status"], "EXHAUSTED_PENDING") @@ -1044,7 +1044,7 @@ def test_bounded_hosted_allocation_reopens_judgment_required_after_full_stop_aud ) ) completed = controller.status()["prs"][0]["allocations"]["hosted"] - self.assertEqual(completed["status"], "CAP_TAPERED") + self.assertEqual(completed["status"], "CAP_AUDITED_STOP") self.assertEqual(completed["completed_count"], 1) self.assertTrue(completed["taper_complete"]) self.assertEqual(evidence[(1, "hosted")][0]["checkpoint"], "hosted-old-head") @@ -1125,7 +1125,7 @@ def test_bounded_hosted_allocation_rejects_current_cli_patch_mismatch(self): with self.assertRaisesRegex(ControllerError, "hosted review cannot run: JUDGMENT_REQUIRED"): controller.resolve_hosted_target() - def test_bounded_hosted_allocation_still_refuses_judgment_required_with_open_findings(self): + def test_bounded_hosted_allocation_records_policy_and_holds_open_findings(self): audit = { "complete": True, "active_reservations": [], @@ -1135,17 +1135,15 @@ def test_bounded_hosted_allocation_still_refuses_judgment_required_with_open_fin } controller, evidence = self.hosted_judgment_allocation_fixture(audit=audit) - with self.assertRaisesRegex( - ControllerError, - "review stop is blocked by an unresolved actionable finding or thread", - ): - self.grant_judgment_hosted_review(controller) + self.grant_judgment_hosted_review(controller) + self.assertIn("1:hosted", controller._state().allocations) + self.assertNotEqual(controller.status()["review_targets"]["hosted"]["status"], "READY") self.assertEqual(len(evidence.stop_audit_calls), 1) - self.assertNotIn("1:hosted", controller._state().allocations) + self.assertIn("1:hosted", controller._state().allocations) self.assertEqual( controller.status()["review_targets"]["hosted"]["status"], - "COMPLETE", + "HELD", ) def test_bounded_hosted_target_stays_judgment_required_when_request_audit_finds_open_threads(self): @@ -1163,14 +1161,13 @@ def test_bounded_hosted_target_stays_judgment_required_when_request_audit_finds_ ): controller.resolve_hosted_target() - def test_bounded_hosted_allocation_does_not_reopen_a_moved_parent(self): + def test_bounded_hosted_allocation_records_despite_moved_parent(self): controller, evidence = self.hosted_judgment_allocation_fixture() evidence[(1, "hosted")][0]["parent_head"] = "9" * 40 - with self.assertRaisesRegex(ControllerError, "allocation requires a coherent current stack identity"): - self.grant_judgment_hosted_review(controller) - - self.assertNotIn("1:hosted", controller._state().allocations) + self.grant_judgment_hosted_review(controller) + self.assertIn("1:hosted", controller._state().allocations) + self.assertNotEqual(controller.status()["review_targets"]["hosted"]["status"], "READY") def test_cross_channel_reopen_uses_reconciled_anchor_and_existing_caches(self): controller, _ = self.hosted_judgment_allocation_fixture() @@ -2427,7 +2424,7 @@ def test_minimum_and_maximum_after_taper_count_only_the_fresh_streak(self): self.assertFalse(final["taper_complete"]) evidence[(1, "cli")].append(self.allocation_evidence(checkpoint="cli-additional-3", channel="cli")) tapered = controller.status()["prs"][0]["allocations"]["cli"] - self.assertEqual(tapered["status"], "CAP_TAPERED") + self.assertEqual(tapered["status"], "CAP_AUDITED_STOP") self.assertEqual(tapered["completed_count"], 3) self.assertTrue(tapered["taper_complete"]) @@ -2476,10 +2473,7 @@ def is_ancestor_unless_wrong_worktree(ancestor, descendant): self.assertEqual(granted["progress"]["completed_count"], 0) self.assertIn("wrong-worktree-cli-capture", allocation["baseline_checkpoints"]) self.assertIn("published-corrected-candidate", allocation["baseline_checkpoints"]) - self.assertTrue(check_stop.call_args_list) - self.assertTrue( - all(call.kwargs.get("require_checkpoint_ancestry") is False for call in check_stop.call_args_list) - ) + self.assertFalse(check_stop.call_args_list) non_fresh = self.make( {1: pr(1, HEAD_1)}, @@ -2649,14 +2643,14 @@ class LegacyEvidence(Evidence): controller = self.make({1: pr(1, HEAD_2)}, history, heads={"feature-1": HEAD_2}) controller.set_stack([1]) controller.git.is_ancestor = lambda _ancestor, _descendant: False - with self.assertRaisesRegex(ControllerError, "accepted findings need a published corrected head"): - controller.decide_allocation( - action="grant", pr=1, channel="hosted", head=HEAD_2, - checkpoint="current-baseline", min_additional_completed=1, - max_additional_completed=1, fresh_taper=True, - reason="retain judged legacy evidence across reconstruction", - ) - self.assertNotIn("1:hosted", controller._state().allocations) + controller.decide_allocation( + action="grant", pr=1, channel="hosted", head=HEAD_2, + checkpoint="current-baseline", min_additional_completed=1, + max_additional_completed=1, fresh_taper=True, + reason="retain judged legacy evidence across reconstruction", + ) + self.assertIn("1:hosted", controller._state().allocations) + self.assertNotEqual(controller.status()["review_targets"]["hosted"]["status"], "READY") def test_fresh_taper_keeps_same_head_audit_and_active_work_holds(self): historical_head = "3f" * 20 @@ -2751,16 +2745,17 @@ def test_fresh_taper_keeps_same_head_audit_and_active_work_holds(self): ancestor != historical_head or descendant != HEAD_1 ) - with self.assertRaisesRegex(ControllerError, expected): - controller.decide_allocation( - action="grant", - pr=1, - channel="cli", - head=HEAD_1, - reason="fresh taper never waives current obligations", - min_additional_completed=1, - fresh_taper=True, - ) + controller.decide_allocation( + action="grant", + pr=1, + channel="cli", + head=HEAD_1, + reason="fresh taper never waives current obligations", + min_additional_completed=1, + fresh_taper=True, + ) + self.assertIn("1:cli", controller._state().allocations) + self.assertNotEqual(controller.status()["review_targets"]["cli"]["status"], "READY") def test_maximum_only_after_taper_reopens_fresh_cli_streak(self): pre_taper_evidence = {(1, "cli"): [self.allocation_evidence(checkpoint="cli-first", channel="cli")]} @@ -2784,7 +2779,7 @@ def test_maximum_only_after_taper_reopens_fresh_cli_streak(self): ) self.assertEqual( pre_taper.status()["prs"][0]["allocations"]["cli"]["status"], - "CAP_TAPERED", + "CAP_AUDITED_STOP", ) evidence = { @@ -3648,29 +3643,58 @@ def test_exact_allocation_records_without_reconciliation_or_git_anchor(self): self.assertEqual(result["progress"]["used"], 0) self.assertEqual(history, [self.scope_timeline_evidence(channel=channel)]) - def test_exact_allocation_preserves_pending_findings_without_stop_audit(self): + def test_human_allocation_forms_grant_and_renew_without_reconciliation_or_git(self): for channel in ("hosted", "cli"): - with self.subTest(channel=channel): - finding = self.allocation_evidence(checkpoint="pending", channel=channel, accepted=1) - history = [finding, self.scope_timeline_evidence(channel=channel)] - controller = self.make( - {1: pr(1, HEAD_1)}, {(1, channel): history}, heads={"feature-1": HEAD_1}, sqlite=True - ) - controller.set_stack([1]) - with patch.object( - controller, "_check_stop_evidence", side_effect=AssertionError("no stop prerequisite") - ): - result = controller.decide_allocation( - action="grant", - pr=1, - channel=channel, - head=HEAD_1, - exact_additional_completed=2, - reason="record allowance while finding remains open", + for allowance in ({}, {"min_additional_completed": 1}, {"max_additional_completed": 3}, {"min_additional_completed": 1, "max_additional_completed": 3}): + for action in ("grant", "renew"): + with self.subTest(channel=channel, allowance=allowance, action=action): + failed = self.allocation_evidence(checkpoint="retained-failure", channel=channel, completed=False, attributable=False, connection_failed=True) + history = [failed, self.scope_timeline_evidence(channel=channel)] + controller = self.make({1: pr(1, HEAD_1)}, {(1, channel): history}, sqlite=True) + controller.set_stack([1]) + if action == "renew": + controller.decide_stop(pr=1, channel=channel, reason="prior human stop") + history_before = list(history) + with ( + patch.object(controller, "_reconciliation", side_effect=AssertionError("policy does not require reconciliation")), + patch.object(controller, "_target", side_effect=AssertionError("policy does not require runnable selection")), + patch.object(controller, "_check_stop_evidence", side_effect=AssertionError("policy does not require stop audit")), + patch.object(controller.git, "merge_base", side_effect=ControllerError("unavailable Git")), + ): + result = controller.decide_allocation(action=action, pr=1, channel=channel, head=HEAD_1, reason="human policy independent of readiness", **allowance) + saved = controller.store.load().allocations[f"1:{channel}"] + self.assertIsNone(saved.merge_base) + self.assertIsNone(saved.patch_id) + self.assertIsNone(saved.stop_basis) + self.assertIn("retained-failure", saved.baseline_checkpoints) + self.assertEqual(history, history_before) + self.assertEqual(result["allocation"].get("min_additional_completed"), allowance.get("min_additional_completed")) + self.assertEqual(result["allocation"].get("max_additional_completed"), allowance.get("max_additional_completed")) + + def test_human_allocation_forms_preserve_pending_findings_without_stop_audit(self): + for allowance in ({}, {"min_additional_completed": 1, "max_additional_completed": 3}, {"exact_additional_completed": 2}): + for channel in ("hosted", "cli"): + with self.subTest(channel=channel): + finding = self.allocation_evidence(checkpoint="pending", channel=channel, accepted=1) + history = [finding, self.scope_timeline_evidence(channel=channel)] + controller = self.make( + {1: pr(1, HEAD_1)}, {(1, channel): history}, heads={"feature-1": HEAD_1}, sqlite=True ) - self.assertIn("pending", result["allocation"]["baseline_checkpoints"]) - self.assertEqual(history[0], finding) - self.assertNotEqual(controller._target(channel, expected_pr=1).status, ReviewStatus.READY) + controller.set_stack([1]) + with patch.object( + controller, "_check_stop_evidence", side_effect=AssertionError("no stop prerequisite") + ): + result = controller.decide_allocation( + action="grant", + pr=1, + channel=channel, + head=HEAD_1, + **allowance, + reason="record allowance while finding remains open", + ) + self.assertIn("pending", result["allocation"]["baseline_checkpoints"]) + self.assertEqual(history[0], finding) + self.assertNotEqual(controller._target(channel, expected_pr=1).status, ReviewStatus.READY) def test_exact_allocation_does_not_stop_at_existing_or_early_taper(self): for channel, prior_count in (("hosted", 1), ("cli", 3)): @@ -3749,10 +3773,48 @@ def test_bounded_dry_result_can_be_renewed_without_stop_authorization(self): reason="explicitly open a fresh bounded review tranche", ) - self.assertTrue(provider.stop_audit_calls) + self.assertFalse(provider.stop_audit_calls) self.assertEqual(renewed["progress"]["status"], "CAP_ACTIVE") self.assertTrue(renewed["allocation"]["reopens_taper"]) + def test_exhausted_cap_advances_discovery_when_taper_audit_cannot_complete(self): + for channel in ("hosted", "cli"): + prior_count = 0 if channel == "hosted" else 2 + 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} + values = {1: pr(1, HEAD_1), 2: pr(2, HEAD_2, "feature-1", HEAD_1)} + controller = self.make(values, evidence, heads={"feature-1": HEAD_1, "feature-2": HEAD_2}, sqlite=True) + controller.set_stack([1, 2]) + controller.decide_allocation(action="grant", pr=1, channel=channel, head=HEAD_1, max_additional_completed=1, reason="one additional result then discovery advances") + completed = self.allocation_evidence(checkpoint="cap-result", channel=channel) + history.append(completed) + state = controller._state() + live, reconciliation = controller._reconciliation(state) + with self.subTest(channel=channel): + progress = controller._allocation_progress( + state.allocations[f"1:{channel}"], history, None, + stack.ReconciliationStatus.UNRECONCILED, state=state, + ) + self.assertEqual(progress["status"], "CAP_EXHAUSTED_PENDING") + self.assertEqual(progress["used"], 1) + self.assertEqual(progress["remaining"], 0) + self.assertTrue(progress["taper_complete"]) + decision = controller._select_review_decision( + state, Channel(channel), live, reconciliation, + {Channel(channel): {1: history, 2: []}}, {1: progress}, [1, 2], + ) + self.assertEqual(decision.target, 2) + with self.subTest(channel=channel, unresolved="thread or summary"): + anchor = controller._anchor(1, live[1], reconciliation.links[1]) + with patch.object(controller, "_check_stop_evidence", side_effect=ControllerError("unresolved thread or summary")): + progress = controller._allocation_progress(state.allocations[f"1:{channel}"], history, anchor, + stack.ReconciliationStatus.COHERENT, state=state, reconciliation_result=reconciliation) + self.assertEqual(progress["status"], "CAP_EXHAUSTED_PENDING") + self.assertIn("unresolved thread or summary", progress["details"]) + self.assertEqual(progress["used"], 1) + self.assertEqual(history[-1], completed) + def test_bounded_renewal_preserves_accepted_finding_and_active_review_holds(self): for blocker, expected_error in ( ("accepted", "unresolved actionable finding or thread"), @@ -3782,17 +3844,18 @@ def test_bounded_renewal_preserves_accepted_finding_and_active_review_holds(self } ) - with self.assertRaisesRegex(ControllerError, expected_error): - controller.decide_allocation( - action="renew", - pr=1, - channel="hosted", - head=HEAD_1, - checkpoint="baseline", - min_additional_completed=1, - max_additional_completed=3, - reason="renew only after current obligations are safe", - ) + controller.decide_allocation( + action="renew", + pr=1, + channel="hosted", + head=HEAD_1, + checkpoint="baseline", + min_additional_completed=1, + max_additional_completed=3, + reason="renew only after current obligations are safe", + ) + self.assertIn("1:hosted", controller._state().allocations) + self.assertNotEqual(controller.status()["review_targets"]["hosted"]["status"], "READY") def test_first_review_can_be_allocated_without_historical_checkpoints(self): controller = self.make({1: pr(1, HEAD_1)}) @@ -5276,7 +5339,7 @@ def test_two_valid_results_invalidate_one_review_allocation(self): self.assertEqual(progress["status"], "INVALID") self.assertIn("multiple completed results match", progress["reason"]) - def test_consumed_dry_and_useful_allocations_cannot_be_renewed(self): + def test_consumed_dry_and_useful_allocations_can_be_renewed_by_human_policy(self): for label, accepted in (("dry", 0), ("useful", 1)): with self.subTest(result=label): evidence = {(1, "hosted"): [self.allocation_evidence(completed=False)]} @@ -5285,16 +5348,16 @@ def test_consumed_dry_and_useful_allocations_cannot_be_renewed(self): self.allocation_evidence(checkpoint=f"allocated-{label}", accepted=accepted) ) - with self.assertRaisesRegex(ControllerError, "consumed or"): - controller.decide_allocation( - action="renew", - pr=1, - channel="hosted", - head=HEAD_1, - reason="do not erase consumed progress", - ) + controller.decide_allocation( + action="renew", + pr=1, + channel="hosted", + head=HEAD_1, + reason="do not erase consumed progress", + ) + self.assertIn("1:hosted", controller._state().allocations) - def test_invalid_progress_with_matching_completed_results_cannot_be_renewed(self): + def test_invalid_progress_can_be_renewed_by_human_policy(self): evidence = {(1, "hosted"): [self.allocation_evidence(completed=False)]} values = {1: pr(1, HEAD_1)} controller = self.grant_allocation(evidence=evidence, values=values) @@ -5308,10 +5371,7 @@ def reject_review_ancestry(ancestor, descendant): return False return original_is_ancestor(ancestor, descendant) - with ( - patch.object(controller.git, "is_ancestor", side_effect=reject_review_ancestry), - self.assertRaisesRegex(ControllerError, "consumed or"), - ): + with patch.object(controller.git, 'is_ancestor', side_effect=reject_review_ancestry): controller.decide_allocation( action="renew", pr=1, @@ -5319,6 +5379,7 @@ def reject_review_ancestry(ancestor, descendant): head=HEAD_2, reason="do not renew after a non-descendant review result", ) + self.assertIn("1:hosted", controller._state().allocations) evidence = {(1, "hosted"): [self.allocation_evidence(completed=False)]} controller = self.grant_allocation(evidence=evidence) @@ -5329,16 +5390,16 @@ def reject_review_ancestry(ancestor, descendant): ) ) - with self.assertRaisesRegex(ControllerError, "consumed or"): - controller.decide_allocation( - action="renew", - pr=1, - channel="hosted", - head=HEAD_1, - reason="do not renew after ambiguous completed results", - ) + controller.decide_allocation( + action="renew", + pr=1, + channel="hosted", + head=HEAD_1, + reason="do not renew after ambiguous completed results", + ) + self.assertIn("1:hosted", controller._state().allocations) - def test_stopped_allocation_cannot_be_renewed(self): + def test_stopped_allocation_can_be_renewed_by_explicit_human_policy(self): evidence = {(1, "hosted"): [self.allocation_evidence(completed=False)]} controller = self.grant_allocation(evidence=evidence) evidence[(1, "hosted")].append(self.allocation_evidence(checkpoint="allocated")) @@ -5352,14 +5413,14 @@ def test_stopped_allocation_cannot_be_renewed(self): self.assertEqual(stopped["stop_basis"], "allocated") self.assertEqual(controller.status()["prs"][0]["channels"]["hosted"], "HUMAN_STOPPED") - with self.assertRaisesRegex(ControllerError, "consumed or stopped"): - controller.decide_allocation( - action="renew", - pr=1, - channel="hosted", - head=HEAD_1, - reason="do not reopen a stopped allocation", - ) + controller.decide_allocation( + action="renew", + pr=1, + channel="hosted", + head=HEAD_1, + reason="do not reopen a stopped allocation", + ) + self.assertIn("1:hosted", controller._state().allocations) def test_pre_review_identity_move_can_still_renew_allocation(self): values = {1: pr(1, HEAD_1)} diff --git a/dev-tools/validation/test_pr_review_sqlite_records_repair.py b/dev-tools/validation/test_pr_review_sqlite_records_repair.py index 4688b39758..50bbc593ac 100644 --- a/dev-tools/validation/test_pr_review_sqlite_records_repair.py +++ b/dev-tools/validation/test_pr_review_sqlite_records_repair.py @@ -140,6 +140,108 @@ def cli_capture( (capture_dir / name).write_bytes(contents) return files + def late_reply_checkpoint(self, *, state="ambiguous", candidate=None, repository="owner/repo", trigger_id="10"): + import test_pr_review_evidence_hosted as fixtures + + payload, record, record_path = fixtures.archived_addressed_reply_fixture(self.common) + payload["data"]["repository"]["pullRequest"]["number"] = fixtures.PR + payload["data"]["repository"]["pullRequest"]["reviewThreads"]["nodes"] = [] + record["anchor"] = { + "child_head": fixtures.HEAD, "parent_identity": "develop", + "parent_head": fixtures.BASE, "merge_base": fixtures.BASE, "patch_id": "archived-patch", + } + record["sqlite_attempt_id"] = "late-reply" + record_path.write_text(json.dumps(record), encoding="utf-8") + self.records.start_attempt( + attempt_id="late-reply", source_pr=fixtures.PR, channel="hosted", + candidate_sha=candidate or fixtures.HEAD, started_at=record["trigger"]["created_at"], + metadata={"repository": repository}, + ) + if state != "started": + self.records.finish_attempt( + "late-reply", state=state, finished_at="2026-09-23T00:02:10Z", + trigger_id=trigger_id, provider_review_id="11", + diagnostic="initial reply has no completion proof", + artifacts={"metadata": '{"initial": "immutable observation"}'}, + ) + body = (f"Hosted: 0 found / 0 accepted / 0 routed · {fixtures.HEAD} · 1 files\n" + "") + at = "2026-09-23T00:03:00Z" + payload["data"]["repository"]["pullRequest"]["comments"]["nodes"].append( + fixtures.comment(40, "owner", body, at) + ) + checkpoint = evidence.parse_checkpoint_comments([{ + "id": 40, "body": body, "created_at": at, "updated_at": at, "author_login": "owner", + }])[0][0] + return payload, checkpoint + + def test_late_verified_reply_preserves_ambiguous_attempt_and_appends_exact_source(self): + payload, checkpoint = self.late_reply_checkpoint() + before = self.records.history(PR) + artifacts = self.records.attempt_artifacts("late-reply") + with patch.object(hosted, "_git_common_dir", return_value=self.common): + preview = repair_provider_checkpoints( + self.records, repo=REPO, pr_number=PR, checkpoints=[checkpoint], actor="operator", + common=self.common, hosted_payload=payload, + ) + self.assertEqual(preview["status"], "preview") + self.assertEqual(self.records.history(PR), before) + result = repair_provider_checkpoints( + self.records, repo=REPO, pr_number=PR, checkpoints=[checkpoint], actor="operator", + common=self.common, hosted_payload=payload, dry_run=False, + ) + after = self.records.history(PR) + replay = repair_provider_checkpoints( + self.records, repo=REPO, pr_number=PR, checkpoints=[checkpoint], actor="operator", + common=self.common, hosted_payload=payload, dry_run=False, + ) + self.assertEqual(result["status"], "complete") + self.assertEqual(replay["status"], "complete") + self.assertEqual(after["attempts"], before["attempts"]) + self.assertEqual(self.records.attempt_artifacts("late-reply"), artifacts) + self.assertEqual(self.records.history(PR), after) + self.assertEqual(len(after["runs"]), 1) + self.assertEqual(after["runs"][0]["counts"], {"found": 0, "accepted": 0, "routed": 0}) + self.assertEqual(after["provider_origins"][0]["provider_id"], "trigger:10") + + def test_late_reply_retains_hold_when_provider_reply_is_still_active(self): + payload, checkpoint = self.late_reply_checkpoint() + response = next( + item for item in payload["data"]["repository"]["pullRequest"]["comments"]["nodes"] + if item.get("databaseId") == 11 + ) + response["body"] = "Reviewing your changes, please wait." + before = self.records.history(PR) + with ( + patch.object(hosted, "_git_common_dir", return_value=self.common), + self.assertRaises(SqliteRecordsRepairError), + ): + repair_provider_checkpoints( + self.records, repo=REPO, pr_number=PR, checkpoints=[checkpoint], actor="operator", + common=self.common, hosted_payload=payload, dry_run=False, + ) + self.assertEqual(self.records.history(PR), before) + + def test_late_reply_rejects_wrong_immutable_attempt_identity(self): + for fields in ({"candidate": "c" * 40}, {"repository": "other/repo"}, {"trigger_id": "99"}): + with self.subTest(fields=fields), tempfile.TemporaryDirectory() as directory: + self.common = Path(directory) + self.database = self.common / "controller.sqlite3" + sqlite_store.SqliteStateStore(self.database).update(lambda state: state) + self.records = SqliteReviewRecords(self.database) + self.records.bootstrap() + payload, checkpoint = self.late_reply_checkpoint(**fields) + before = self.records.history(PR) + with ( + patch.object(hosted, "_git_common_dir", return_value=self.common), + self.assertRaisesRegex(SqliteRecordsRepairError, "immutable ambiguous attempt"), + ): + repair_provider_checkpoints( + self.records, repo=REPO, pr_number=PR, checkpoints=[checkpoint], + actor="operator", common=self.common, hosted_payload=payload, dry_run=False, + ) + self.assertEqual(self.records.history(PR), before) + def record_cli_attempt( self, *, diff --git a/dev-tools/validation/test_pr_review_state_stack.py b/dev-tools/validation/test_pr_review_state_stack.py index f02e03efbb..223d9a9b33 100644 --- a/dev-tools/validation/test_pr_review_state_stack.py +++ b/dev-tools/validation/test_pr_review_state_stack.py @@ -181,7 +181,7 @@ def test_review_allocation_accepts_decision_time_bounds_without_a_pinned_checkpo self.assertIsNone(restored.baseline_checkpoint) self.assertEqual(restored.min_additional_completed, 2) - def test_exact_equal_bound_allowance_roundtrips_unavailable_git_audit_facts(self): + def test_human_allowance_roundtrips_unavailable_git_audit_facts(self): allocation = ReviewAllocation( pr=2827, channel="cli", @@ -197,8 +197,10 @@ def test_exact_equal_bound_allowance_roundtrips_unavailable_git_audit_facts(self ) self.assertEqual(ReviewAllocation.from_dict(allocation.to_dict()), allocation) for changed in ({"max_additional_completed": 3}, {"min_additional_completed": None}): - with self.subTest(changed=changed), self.assertRaises(StateError): - ReviewAllocation.from_dict({**allocation.to_dict(), **changed}) + with self.subTest(changed=changed): + restored = ReviewAllocation.from_dict({**allocation.to_dict(), **changed}) + self.assertIsNone(restored.merge_base) + self.assertIsNone(restored.patch_id) def test_bounded_review_allocation_rejects_missing_baseline_or_invalid_cap(self): base = { From 054856f595dcdaf64960c3b4bf36c3371bc9f580 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 12:46:06 +1300 Subject: [PATCH 4/4] Preserve configured stacked parent identity in human review allowances --- dev-tools/pr_review/controller.py | 11 +++++- .../validation/test_pr_review_controller.py | 36 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/dev-tools/pr_review/controller.py b/dev-tools/pr_review/controller.py index 0f51007fa9..b8700f4e21 100644 --- a/dev-tools/pr_review/controller.py +++ b/dev-tools/pr_review/controller.py @@ -5731,7 +5731,16 @@ def decide_allocation( raise ControllerError("Git provider returned an empty patch identity") except (ControllerError, OSError, ValueError, subprocess.SubprocessError): merge_base, patch_id = None, None - current = AnchorFacts(pr, item.head, item.base_ref, item.base_tip, merge_base, patch_id) + parent_identity = item.base_ref + try: + for parent_pr in reversed(state.ordered_prs[:state.ordered_prs.index(pr)]): + parent = _live(self._require_github().pull_request(parent_pr), parent_pr) + if not parent.merged: + parent_identity = stack.ParentLink(pr, parent_pr, parent.head_ref, parent.head).identity + break + except (ControllerError, KeyError, OSError, RuntimeError, TypeError, ValueError, subprocess.SubprocessError): + pass + current = AnchorFacts(pr, item.head, parent_identity, item.base_tip, merge_base, patch_id) if normalized_head != item.head: raise ControllerError("allocation head does not match the live pull-request head") if self._head_repository_problem(item): diff --git a/dev-tools/validation/test_pr_review_controller.py b/dev-tools/validation/test_pr_review_controller.py index 28b714359f..057148590d 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -1001,6 +1001,42 @@ def grant_judgment_hosted_review(controller): fresh_taper=True, ) + def test_stacked_human_allocation_keeps_configured_parent_identity_without_reconciliation(self): + for exact in (False, True): + with self.subTest(exact=exact): + controller, evidence = self.hosted_judgment_allocation_fixture() + controller.github.values[2] = pr(2, BASE) + controller.github.values[1] = pr(1, HEAD_3, base_ref="feature-2", base_tip=BASE) + controller.git.heads["feature-2"] = BASE + for channel in ("hosted", "cli"): + for row in evidence[(1, channel)]: + if row.get("completed"): + row["parent_identity"] = "2" + controller = self.make( + controller.github.values, evidence, heads=controller.git.heads, sqlite=True, + ) + controller.set_stack([2, 1]) + for channel in ("hosted", "cli"): + controller.decide_stop(pr=2, channel=channel, head=BASE, reason="parent review discovery complete") + kwargs = ({"exact_additional_completed": 1} if exact else { + "min_additional_completed": 1, "max_additional_completed": 1, "fresh_taper": True, + }) + with patch.object(controller, "_reconciliation", side_effect=AssertionError("policy has no readiness gate")): + controller.decide_allocation( + action="grant", pr=1, channel="hosted", head=HEAD_3, + reason="review the corrected stacked child", **kwargs, + ) + saved = controller._state().allocations["1:hosted"] + self.assertEqual(saved.parent_identity, "2") + self.assertEqual(saved.parent_head, BASE) + if not exact: + self.assertEqual(controller.status()["review_targets"]["hosted"]["status"], "READY") + self.assertEqual(controller.resolve_hosted_target().snapshot.number, 1) + controller.github.values[2] = pr(2, HEAD_1) + controller.git.heads["feature-2"] = HEAD_1 + with self.assertRaises(ControllerError): + controller.resolve_hosted_target() + def test_bounded_hosted_allocation_reopens_judgment_required_after_full_stop_audit(self): controller, evidence = self.hosted_judgment_allocation_fixture()