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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ ownership and the contributor routine that keeps documentation current.

For a picture of the whole flow, see the [workflow diagrams](docs/WORKFLOW.md).

`loopzero status` prints where the current branch is in that sequence.
`loopzero status` prints where the current branch is in that sequence. It
requires authenticated access to the configured GitHub repository even before
a PR exists.
`loopzero resolve` lists the open blocking findings with their ids;
`loopzero resolve <id> "<what changed>"` replies in that thread and resolves it.

Expand Down
20 changes: 12 additions & 8 deletions SETUP.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,19 +241,22 @@ Lock the vault and remove `BW_SESSION` before starting the agent.
### Several subscription accounts (optional)

`scripts/ai-accounts/` rotates Claude and Codex subscription accounts behind the plain
`claude`, `codex` and `loopzero` commands. Install the monitor and its three shims:
`claude`, `codex` and `loopzero` commands. Install the monitor and its three shims
from the [pinned source checkout](#connect-your-agent):

```sh
install -m 755 scripts/ai-accounts/ai-accounts ~/.local/bin/
ACCOUNTS=~/.local/share/loopzero/source/scripts/ai-accounts
install -m 755 "$ACCOUNTS/ai-accounts" ~/.local/bin/
mkdir -p ~/.local/lib/ai-accounts/bin
for n in claude codex loopzero; do ln -sf ~/.local/bin/ai-accounts ~/.local/lib/ai-accounts/bin/$n; done
```

Put the shims first on PATH by making this the last line of `~/.profile` and
`~/.bashrc`, after anything that prepends `~/.local/bin`:
`export PATH="$HOME/.local/lib/ai-accounts/bin:$PATH"`. Point an agent host's binary
path at `~/.local/lib/ai-accounts/bin/claude` (and `codex`). Enable the monitor by copying
the two systemd units to `~/.config/systemd/user/`, then
path at `~/.local/lib/ai-accounts/bin/claude` (and `codex`). Copy
`"$ACCOUNTS/ai-accounts.service"` and `"$ACCOUNTS/ai-accounts.timer"` to
`~/.config/systemd/user/`, then run
`systemctl --user enable --now ai-accounts.timer`.

- Claude accounts are long-lived tokens: run `claude setup-token` per account and
Expand Down Expand Up @@ -325,10 +328,11 @@ loopzero start hello-loopzero # new worktree + branch; cd to the printed
$EDITOR .loopzero/task.md # fill Context, Problem, Goal and Acceptance
```

Use the [workflow diagram](docs/WORKFLOW.md#1-from-idea-to-merged) to navigate
the contract's [six steps](core/CONTRACT.md#the-six-steps). Run `loopzero status`
to see the next step. See [Blockers](core/CONTRACT.md#blockers) for how to
resolve review findings.
Make and commit a change in the task worktree, then run `loopzero check` there.
Afterward, `loopzero status` shows the next step and requires authenticated
access to the configured GitHub repository even before a PR exists. See the
[workflow diagram](docs/WORKFLOW.md#1-from-idea-to-merged) and
[Blockers](core/CONTRACT.md#blockers) for the rest of the workflow.

## Removing an abandoned task worktree

Expand Down
78 changes: 55 additions & 23 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -776,24 +776,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 @@ -808,7 +794,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 @@ -817,6 +802,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 @@ -839,7 +828,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 @@ -884,6 +873,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 @@ -1113,22 +1143,24 @@ def _save_review(wt: Path, result: ReviewResult, publication: dict | None = None
_write_json_atomically(path, 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 @@ -75,6 +75,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