Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion dev-tools/pr_review/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,16 @@ Hosted findings and their associated source/incoming routes expose `display_seve

Provider runs may include `duration_seconds` from an exact completed attempt or an identity-validated retained checkpoint/capture; evaluated missing, invalid or conflicting duration evidence returns `duration_seconds: null`, which is authoritative unknown. Consumers may use legacy fallback only when the field is absent, never when it is null. Import event timestamps are never treated as elapsed review time. Reads make no provider requests or historical corrections.

For one retained ambiguous Hosted reply whose complete public history and immutable prior capture prove a finished zero-result response, `records repair-provider` supports an exact response selector paired with its original attempt:

```sh
dev-tools/pr-review records repair-provider --pr <number> --repo <owner/name> \
--response-id <reply comment ID> --attempt-id <exact ambiguous attempt ID> \
--actor <operator> --scope broad [--database <path>]
```

The default is a preview; repeat with `--apply` only after reviewing that preview. This recovery mode accepts only the captured reply, full immutable request anchor, complete current response window, and exact archived-thread updates already proved against the prior completed attempt. It refuses unknown or changed reply text, substantive findings, conflicting identities, incomplete history, and changed archive evidence. It appends one zero-count source run, its exact archived artifacts, and the provider origin last; exact retries reuse those same identities. The original ambiguous state and capture remain unchanged. This repair does not itself publish a checkpoint or grant readiness. The exact recovered zero-result run may later use the explicit `records source finalize` publication path below; that path appends only publication intent/events to the original ambiguous attempt metadata and retains its state, provider identity, capture, terminal times, and immutable response origin. No other imported or manual run gains publication eligibility.

```sh
dev-tools/pr-review routes --target-pr <number>
dev-tools/pr-review routes --unassigned
Expand Down Expand Up @@ -265,7 +275,7 @@ After adjudicating all source findings, freeze counts and publish/reuse the cano
dev-tools/pr-review records source finalize --run-id <run ID>
```

The CLI finalization command publishes completed native Hosted/CLI runs after freezing their counts; manual/subagent runs remain local. The underlying store operation stays SQL-only for imports, captures, repairs and subagent completion. SQL finalization and GitHub publication are not atomic: counts can already be frozen when publication fails. The command then reports failure; repeat the same finalization to recover/reuse publication safely. This command derives the canonical counts, full reviewed SHA, file count, duration and provider markers from completed immutable native evidence. It supports CLI captures and new Hosted captures with verified request-time candidate file count and retained exact trigger attribution. Older Hosted captures missing either field fail closed and retain the historical manual workflow; no current diff or agent-supplied count substitutes for them. Advancing the live PR head does not invalidate its older reviewed checkpoint. Candidate file count describes the captured review scope; provider completion and coverage still require adjudication and do not imply physical inspection of every file. Publication adds no fix proof, allocation override, CI result, or merge permission.
The CLI finalization command publishes completed native Hosted/CLI runs after freezing their counts; manual/subagent runs remain local. It also accepts only the exact deterministic zero-result run imported by the ambiguous Hosted reply recovery above, using its original request file count, reviewed head, elapsed trigger window, and response marker. For that exception, the publication intent and append-only events live in the original ambiguous attempt metadata; they do not link the attempt to a run or rewrite its terminal history or provider origin. Runtime associates the newly published comment with the recovered run only when that durable audit binds the exact public comment. The underlying store operation stays SQL-only for imports, captures, repairs and subagent completion. SQL finalization and GitHub publication are not atomic: counts can already be frozen when publication fails. The command then reports failure; repeat the same finalization to recover/reuse publication safely. This command derives the canonical counts, full reviewed SHA, file count, duration and provider markers from completed immutable evidence. It supports CLI captures and new Hosted captures with verified request-time candidate file count and retained exact trigger attribution. Older Hosted captures missing either field fail closed and retain the historical manual workflow; no current diff or agent-supplied count substitutes for them. Advancing the live PR head does not invalidate its older reviewed checkpoint. Candidate file count describes the captured review scope; provider completion and coverage still require adjudication and do not imply physical inspection of every file. Publication adds no fix proof, allocation override, CI result, or merge permission.

The structured result includes `publication` with `status: published|reused`, `comment_id`, `comment_url`, and the canonical `body`. Publishers share the existing lock primitive and retain a pre-POST intent in the existing attempt metadata. Complete paginated GitHub history and verified repository/publisher identity permit reuse of semantically matching canonical comments, including verified commit links and harmless whitespace, and reject conflicting identities or counts. An uncertain POST is recovered by reading history; if the exact comment is not visible, retries refuse another POST and retain the intent. Retry the command later for read recovery; do not manually repost or overwrite historical comments.

Expand Down
66 changes: 57 additions & 9 deletions dev-tools/pr_review/checkpoint_publication.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,22 +68,47 @@ def checkpoint_body(store, *, repo, source_pr, run_id):
history = store.history(source_pr, include_display=False)
runs = [run for run in history["runs"] if run["run_id"] == run_id]
attempts = [attempt for attempt in store.attempt_history(source_pr) if attempt["run_id"] == run_id]
if len(runs) != 1 or len(attempts) != 1:
if len(runs) != 1:
_refuse("checkpoint requires exactly one finalized source run")
run = runs[0]
recovered = False
attempt = None
if len(attempts) == 1 and attempts[0]["attempt_id"] == run_id:
attempt = attempts[0]
if (run["channel"] not in {"cli", "hosted"} or run["outcome"] != "completed"
or run["attributable"] is not True or run["finalized"] is not True
or attempt["channel"] != run["channel"] or attempt["state"] != "completed"
or attempt["candidate_sha"] != run["source_head"] or attempt["run_id"] != run_id):
_refuse("checkpoint requires completed attributable finalized native evidence")
elif not attempts and run.get("channel") == "hosted":
try:
from .sqlite_records_repair import verify_ambiguous_reply_import_for_publication

recovered = verify_ambiguous_reply_import_for_publication(
store, repo=repo, pr_number=source_pr, run_id=run_id
)
except (ValueError, TypeError, KeyError) as exc:
raise ReviewRecordsError(f"checkpoint recovery proof is unavailable: {exc}") from exc
run = recovered["run"]
attempt = recovered["attempt"]
else:
_refuse("checkpoint requires exactly one native source run and matching attempt")
run, attempt = runs[0], attempts[0]
channel = run["channel"]
if (channel not in {"cli", "hosted"} or run["outcome"] != "completed"
or run["attributable"] is not True or run["finalized"] is not True
or attempt["attempt_id"] != run_id or attempt["channel"] != channel
or attempt["state"] != "completed" or attempt["candidate_sha"] != run["source_head"]):
_refuse("checkpoint requires completed attributable finalized native evidence")
head, duration, counts = run["source_head"], attempt["duration_seconds"], run["counts"]
head, duration, counts = run["source_head"], (
recovered["checkpoint"].duration_seconds if recovered else attempts[0]["duration_seconds"]
), run["counts"]
if (not isinstance(head, str) or not evidence.EXACT_SHA.fullmatch(head)
or type(duration) is not int or duration < 0
or any(type(counts.get(key)) is not int or counts[key] < 0 for key in ("found", "accepted", "routed"))
or counts["accepted"] + counts["routed"] > counts["found"]):
_refuse("checkpoint source head, counts or duration is invalid")
if channel == "cli":
if recovered:
checkpoint = recovered["checkpoint"]
if checkpoint.file_count is None or checkpoint.file_count <= 0:
_refuse("recovered Hosted checkpoint lacks its captured request file count")
files = checkpoint.file_count
marker = f"<!-- firemud-hosted-review: {checkpoint.hosted_review_id} -->"
elif channel == "cli":
if not evidence.RUN_ID.fullmatch(run_id):
_refuse("native CLI run has invalid marker identity")
snapshot = store.cli_capture_snapshot(run_id, source_pr=source_pr)
Expand Down Expand Up @@ -240,6 +265,29 @@ def publish_checkpoint(store, *, repo, source_pr, run_id, adapter=github):
comment = matching(adapter.fetch_api_endpoint(endpoint))
fresh = store.reserve_checkpoint_publication(run_id, json.dumps(intent, sort_keys=True))
if comment is not None:
_, recovered = store._checkpoint_publication_target(
run_id, repository=repo, source_pr=source_pr
)
if recovered:
state = store.checkpoint_publication_state(run_id)
bound = [
event
for event in state["events"]
if event.get("type") in {"post_outcome", "reused"}
and event.get("comment_id") == comment["id"]
]
conflicts = [
event
for event in state["events"]
if event.get("type") in {"post_outcome", "reused"}
and event.get("comment_id") is not None
and event.get("comment_id") != comment["id"]
]
if conflicts:
_refuse("recovered checkpoint publication audit conflicts with visible comment identity")
if not bound:
_append(store, run_id, state, {"type": "reused", "decision_id": None,
"comment_id": comment["id"]})
return _result(intent, comment, "reused")
if not fresh:
_refuse("prior checkpoint POST may have occurred; no verified comment is visible; retry read recovery later")
Expand Down
50 changes: 49 additions & 1 deletion dev-tools/pr_review/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

import argparse
import dataclasses
import fcntl
import hashlib
import json
import os
import re
import stat
import sys
Expand Down Expand Up @@ -59,6 +61,21 @@ def parse_args(self, args=None, namespace=None):
)
):
self.error("--exact-additional-completed cannot be combined with min or max additional-completed bounds")
if getattr(parsed, "records_command", None) == "repair-provider":
response_id = getattr(parsed, "response_id", None)
attempt_id = getattr(parsed, "attempt_id", None)
selected_checkpoint = getattr(parsed, "checkpoint_id", None)
selected_all = getattr(parsed, "all", False)
if response_id is None and attempt_id is not None:
self.error("--attempt-id requires --response-id")
if response_id is not None and (attempt_id is None or selected_checkpoint is not None or selected_all):
self.error(
"--response-id requires exactly one --attempt-id and cannot be combined with checkpoint selectors"
)
if response_id is None and selected_checkpoint is None and not selected_all:
self.error("repair-provider requires --checkpoint-id, --all, or --response-id with --attempt-id")
if response_id is not None and getattr(parsed, "continue_on_error", False):
self.error("--continue-on-error is only valid with --all")
return parsed


Expand Down Expand Up @@ -329,9 +346,15 @@ def records_database(command: argparse.ArgumentParser) -> None:
help="preview or replay exact public provider checkpoints into SQLite",
)
provider_repair.add_argument("--pr", required=True, type=_positive_int)
repair_selection = provider_repair.add_mutually_exclusive_group(required=True)
repair_selection = provider_repair.add_mutually_exclusive_group()
repair_selection.add_argument("--checkpoint-id", action="append", type=_positive_int)
repair_selection.add_argument("--all", action="store_true")
repair_selection.add_argument(
"--response-id",
type=_positive_int,
help="recover one exact captured ambiguous Hosted reply; requires --attempt-id",
)
provider_repair.add_argument("--attempt-id", help="exact retained ambiguous Hosted attempt for --response-id")
provider_repair.add_argument("--repo", help="owner/name; defaults to the current GitHub repository")
provider_repair.add_argument("--actor", required=True)
provider_repair.add_argument("--scope", required=True, choices=("broad", "narrow"))
Expand Down Expand Up @@ -1365,6 +1388,31 @@ def _dispatch_records(args: argparse.Namespace) -> tuple[Any, int]:
if args.records_command == "repair-provider":
store.history(args.pr)
repo = github.infer_repo(args.repo)
if args.response_id is not None:
if args.coverage_limit:
raise CliError("exact response recovery does not accept checkpoint coverage limits")
record_path = hosted.default_trigger_record_path(repo, args.pr, store.path.parent.parent)
descriptor = hosted._with_lock(record_path)
try:
try:
payload = github.fetch_pull_request(repo, args.pr)
except (OSError, RuntimeError, TypeError, ValueError) as exc:
raise CliError("could not read complete Hosted response history") from exc
result = sqlite_records_repair.repair_ambiguous_hosted_reply(
store,
repo=repo,
pr_number=args.pr,
attempt_id=args.attempt_id,
response_id=args.response_id,
actor=args.actor,
scope=args.scope,
hosted_payload=payload,
dry_run=not args.apply,
)
finally:
fcntl.flock(descriptor, fcntl.LOCK_UN)
os.close(descriptor)
return {"api_version": 1, "result": result}, 0 if result["status"] != "partial" else 2
checkpoints, payload = _provider_checkpoints(args, repo)
if args.continue_on_error:
if not args.all:
Expand Down
Loading
Loading