Skip to content
Closed
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
44 changes: 22 additions & 22 deletions core/CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,21 @@ own delivery state; `.loopzero/` holds task text and local receipts.
problem, context, acceptance, base SHA. Write the PR, like any issue or
design doc you write, for the project owner under [Reporting](#reporting).
2. Implement, commit, then `loopzero check`: run `workflow.toml`
`[checks].commands` in the sandbox. Its exit code is the verdict. For a long
check under a [provider-portable handoff](../docs/DELEGATION.md#provider-portable-handoff),
open the draft in step 3 before starting the check.
`[checks].commands` in the sandbox. Open the draft before a long check under a
[provider-portable handoff](../docs/DELEGATION.md#provider-portable-handoff).
3. `loopzero pr` pushes and opens a **draft** PR from the task text plus
generated Validation checks. Later calls sync narrative, preserving live
Validation, Review and extra sections; `check` refreshes only its checks
block. Drafts need no clean review.
4. `loopzero review` reviews the exact head, independently by default, and
posts one GitHub review with inline findings: exit 0 `approve`,
5 `request_changes`.
5. `loopzero ready --wait` marks ready PRs ready for review. It also activates
drafts blocked only by missing/skipped checks to trigger CI, even with
mergeability pending. Without waiting, activation exits 3.
Both waiters use `--wait[=SECONDS]` (default 1800) on the unchanged head.
Zero seconds can still activate or enqueue a PR. Pending mergeability can
time out (exit 3) with green checks. `loopzero merge --cancel` requests
Mergify removal without `--wait`.
Green can precede CI scheduling. After two minutes with only missing checks
and none pending, inspect scheduling, triggers and permissions, then retry.
4. `loopzero review` defaults to independent review of the exact head and posts
one GitHub review with inline findings. Approval exits 0, changes requested 5.
5. `loopzero ready --wait` marks eligible PRs ready and activates drafts with
only missing/skipped checks even with mergeability pending. Activation without a
wait exits 3. Both waiters use `--wait[=SECONDS]` (default 1800) on the same
head. Zero can activate or enqueue. Mergeability can time out (exit 3)
with green checks. `loopzero merge --cancel` requests Mergify removal without `--wait`.
Green can precede CI scheduling. After two minutes of missing checks with
none pending, inspect scheduling, triggers and permissions, then retry.
6. After step 5 exits 0, run from a durable directory such as `/tmp`
using the absolute path to the task worktree.

Expand All @@ -37,10 +33,9 @@ own delivery state; `.loopzero/` holds task text and local receipts.
```

Merge rechecks readiness, uses the configured strategy, verifies the landed
SHA, and deletes the branch and worktree. If cleanup warns, the merge landed.
Follow the recovery step it names. A queue initially enqueues;
`--wait` shares a budget across source-check and landing waits. Enqueueing
without `--wait` returns 0 without cleanup.
SHA and deletes the branch and worktree. A cleanup warning follows a verified
merge. Follow its recovery step. Queueing without `--wait` exits 0 without
cleanup. With `--wait`, source checks and landing share one budget.

Merge is authorized by default under [merge authority](#merge-authority).

Expand Down Expand Up @@ -283,9 +278,14 @@ meta-directives; reviewers load no instruction files or skills from the reviewed

## Failure

Fail closed on missing tools and command errors, preserve the failing command
and output tail, and keep a short, safe detail about the cause or stage when
operator-facing code wraps an error. Stop on terminal failures or quota errors.
Fail closed on missing tools or command errors. Preserve the command and output
tail, name the cause or stage safely, and stop on terminal failures or quota errors.
`check` exits 0 when stages pass, including local dirty runs that cannot satisfy
readiness. Exit 1 can mean a failed stage, a discarded or unverified result, or
a command error. Read the diagnostic and verify the receipt before classifying
the failure. Exit 2 covers invalid arguments and sandbox unavailability in
`check` or fresh `review`.

Exit 3 means waiting or timeout. Review exits 4 when independent review is
unavailable and 5 when changes are requested. Interruption exits 130.

Expand Down
78 changes: 55 additions & 23 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -813,24 +813,10 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
kind, reviewed = _decide_kind(
_pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head
)
publication_context = {"repo": config.repo, "number": pr.number, "publisher": publisher}
if args.repost:
authors = runners.author_families(wt, head, _primary_base(wt, config))
excluded = [family for family in config.reviewers if family in authors]
result = _load_review(wt, head, kind)
if result.fallback and result.family not in excluded:
raise CliError(
f"saved review claims a same-family fallback, but {result.family} is not a configured "
"reviewer family that contributed to this PR lineage; run without --repost"
)
if not result.fallback and not any(family not in authors for family in config.reviewers):
raise IndependentReviewerUnavailable(
_independence_message(authors, excluded, [])
)
if result.family in authors and not result.fallback:
raise IndependentReviewerUnavailable(
f"saved reviewer family {result.family} contributed to this PR lineage; "
"run without --repost to obtain an independent review"
)
candidates, excluded = _repost_reviewer_families(wt, config, head, result)
publication = json.loads(_review_file(wt, head, kind).read_text()).get("publication")
if publication is not None:
if (not isinstance(publication, dict) or publication.get("repo") != config.repo
Expand All @@ -845,7 +831,6 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
else:
reviews = _pr_reviews(config.repo, pr.number)
# Exact read-back above may confirm an older published note; a new post needs the current form.
candidates = [family for family in config.reviewers if family not in authors]
if result.fallback and not _published_fallback(result.fallback, candidates, excluded):
raise CliError("saved fallback note is not in the published form; run without --repost")
allowed, _ = _decide_kind(
Expand All @@ -854,6 +839,10 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
if allowed != kind:
raise CliError("saved review kind differs from the remaining review budget")
else:
if args.model is None and args.effort is None and _has_recoverable_review(
wt, config, head, kind, publication_context,
):
raise CliError(f"saved {kind} review for {head[:12]}; run `loopzero review --repost`")
try:
result = _run_review(wt, config, head, kind, reviewed, args.model, args.effort,
runtime_source=runtime_source, publication=(config.repo, pr.number, publisher))
Expand All @@ -876,7 +865,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
raise CliError("native publication context changed; HOLD")
if args.repost:
prefix = _repost_prefix(result)
_save_review(wt, result, {"repo": config.repo, "number": pr.number, "publisher": publisher})
_save_review(wt, result, publication_context)
token = _refresh_publisher_token(token, publisher)
try:
github.post_review(
Expand Down Expand Up @@ -922,6 +911,47 @@ def _review_verdict(result: ReviewResult) -> int:
return 0 if result.verdict == "approve" else 5 # the exit code is the verdict, as for check


def _repost_reviewer_families(
wt: Path, config: Config, head: str, result: ReviewResult,
) -> tuple[list[str], list[str]]:
authors = runners.author_families(wt, head, _primary_base(wt, config))
excluded = [family for family in config.reviewers if family in authors]
if result.fallback and result.family not in excluded:
raise CliError(
f"saved review claims a same-family fallback, but {result.family} is not a configured "
"reviewer family that contributed to this PR lineage; run without --repost"
)
if not result.fallback and not any(family not in authors for family in config.reviewers):
raise IndependentReviewerUnavailable(
_independence_message(authors, excluded, [])
)
if result.family in authors and not result.fallback:
raise IndependentReviewerUnavailable(
f"saved reviewer family {result.family} contributed to this PR lineage; "
"run without --repost to obtain an independent review"
)
return [family for family in config.reviewers if family not in authors], excluded


def _has_recoverable_review(
wt: Path, config: Config, head: str, kind: str, publication: dict,
) -> bool:
other_kind = "delta" if kind == "primary" else "primary"
if not _review_file(wt, head, kind).exists() or _review_file(wt, head, other_kind).exists():
return False
try:
result = _load_review(wt, head, kind, publication=publication)
candidates, excluded = _repost_reviewer_families(wt, config, head, result)
if result.fallback and not _published_fallback(result.fallback, candidates, excluded):
return False
evidence = runners.codex_evidence(result)
except (CliError, runners.RunnerBadOutput):
return False
return evidence is None or (evidence["repo"], evidence["pr"], evidence["publisher"]) == (
publication["repo"], publication["number"], publication["publisher"],
)


def _repost_prefix(result: ReviewResult) -> str:
sessions = result.provenance["session_ids"]
return review_marker(result.head, result.kind, "repost") + "\n" + (
Expand Down Expand Up @@ -1153,22 +1183,24 @@ def _save_review(wt: Path, result: ReviewResult, publication: dict | None = None
_write_json_atomically(directory, path.name, data)


def _load_review(wt: Path, head: str, kind: str) -> ReviewResult:
def _load_review(
wt: Path, head: str, kind: str, *, publication: dict | None = None,
) -> ReviewResult:
path = _review_file(wt, head, kind)
if not path.exists():
raise CliError(f"no saved {kind} review for {head[:12]} at {path}; run without --repost")
try:
data = json.loads(path.read_text())
except (json.JSONDecodeError, OSError) as exc:
except (ValueError, OSError) as exc:
raise CliError(f"{path} is not runner-produced: invalid saved review") from exc
if not isinstance(data, dict):
raise CliError(f"{path} is not runner-produced: invalid saved review")
if data.get("head") != head:
raise CliError(f"{path} holds a review of {str(data.get('head'))[:12]}, not HEAD {head[:12]}")
try:
data.pop("publication", None)
if data.get("kind") != kind:
raise ValueError("saved review kind mismatch")
saved_publication = data.pop("publication", None)
if data.get("kind") != kind or (publication is not None and saved_publication != publication):
raise ValueError("saved review kind or publication mismatch")
findings = tuple(Finding(**f) for f in data["findings"])
# Ordinary receipts written before pair retirement still carry these defaults.
for field, default in (("members", []), ("reconciliation", ""),
Expand Down
45 changes: 45 additions & 0 deletions tests/test_review_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,51 @@ def assert_single_publication(gh, fake_bin):
assert len([c for c in gh.calls if "--input" in c]) == 1


@pytest.mark.parametrize("override", [None, "pr", "head", "raw", "bytes", "effort"])
def test_plain_review_surfaces_receipt_after_interruption_before_post(
wt, gh, fake_bin, monkeypatch, capsys, override,
):
head = support.prepare_review(wt, gh, fake_bin)
reviewer = fake_bin / "claude"
reviewer.write_text(reviewer.read_text().replace(
"#!/bin/sh\n", f'#!/bin/sh\nprintf "run\\n" >> "{fake_bin}/claude.runs"\n'))
original = github.post_review

def interrupt(*args, **kwargs):
raise KeyboardInterrupt

monkeypatch.setattr(github, "post_review", interrupt)
assert run(capsys, "review")[0] == 130
monkeypatch.setattr(github, "post_review", original)

path = cli._review_file(wt, head, "primary")
saved = path.read_bytes()
if override in {"pr", "head", "raw"}:
payload = json.loads(saved)
if override == "pr":
payload["publication"]["number"] = 999
else:
payload[override] = "invalid"
path.write_text(json.dumps(payload))
if override == "bytes":
path.write_bytes(b"\xff")
args = ["--effort", "high"] if override == "effort" else []
code, _out, err = run(capsys, "review", *args)

if override is None:
assert code == 1 and "loopzero review --repost" in err
assert path.read_bytes() == saved
assert not any("--input" in c for c in gh.calls)
assert run(capsys, "review", "--repost")[0] == 0
assert (fake_bin / "claude.runs").read_text().splitlines() == ["run"]
assert sum(
c["argv"][1] == support.post_key().split()[1] and "--input" in c for c in gh.calls
) == 1
else:
assert code == 0, err
assert (fake_bin / "claude.runs").read_text().splitlines() == ["run", "run"]


@pytest.mark.parametrize("kind", ["primary", "delta"])
@pytest.mark.parametrize("verdict", [0, 5])
@pytest.mark.parametrize("interrupted", [False, True, "timeout"])
Expand Down
Loading