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
2 changes: 1 addition & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ verdict. Pending, dismissed, conflicting or changing evidence blocks recovery.
only an explicit retry after complete absence may publish again. The existing
self-review rejection fallback to COMMENT remains a separate transport rule.

Private review receipts and sidecars live under the task worktree's `.loopzero/` and disappear when guarded merge cleanup removes the worktree. GitHub retains the published review evidence.
Private review receipts, sidecars and malformed output excerpts live under the task worktree's `.loopzero/` and disappear when guarded merge cleanup removes the worktree. GitHub retains the published review evidence.

Private agent transcripts and metrics ledgers do not belong in this guide or in
a new persistent store.
Expand Down
40 changes: 25 additions & 15 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1087,7 +1087,7 @@ def _run_review(
task = worktree.task_text(wt)
authors = runners.author_families(wt, head, lineage_base)
candidates = [family for family in config.reviewers if family not in authors]
failures: list[str] = []
errors: dict[str, tuple[str, str]] = {}
excluded = [family for family in config.reviewers if family in authors]
def select(family: str) -> Callable[..., ReviewResult]:
settings = config.review.get(family)
Expand Down Expand Up @@ -1121,7 +1121,7 @@ def select(family: str) -> Callable[..., ReviewResult]:
attempts = candidates + excluded
for index, family in enumerate(attempts):
if family in unusable:
failures.append(unusable[family])
errors[family] = unusable[family], ""
continue
if family in excluded and not fallback:
fallback = ("independent reviewers failed: " + "; ".join(reasons)
Expand All @@ -1143,33 +1143,43 @@ def select(family: str) -> Callable[..., ReviewResult]:
break
except RUNNER_FAILURES as exc:
reason, detail, fallback_reason = _review_failure(family, exc)
failures.append(detail)
errors[family] = detail, exc.tail if isinstance(exc, runners.RunnerMalformedOutput) else ""
reasons.append(f"{family}: {fallback_reason}")
if any(next_family in selected for next_family in attempts[index + 1:]):
print(f"reviewer {family} unavailable: {reason}", file=sys.stderr)
else:
raise IndependentReviewerUnavailable(
_independence_message(authors, excluded, failures)
_independence_message(authors, excluded, [detail for detail, _ in errors.values()])
+ _save_review_failure_output(wt, head, kind, errors)
)
return dataclasses.replace(result, fallback=fallback)


def _save_review_failure_output(wt: Path, head: str, kind: str, errors: dict[str, tuple[str, str]]) -> str:
if not (fragments := {family: tail for family, (_, tail) in errors.items() if tail}):
return ""
path = wt / ".loopzero" / f"reviewer-output-{head[:12]}-{kind}.json"
try:
with _lock_task_state(wt) as directory:
_write_json_atomically(directory, path.name, fragments)
except OSError as exc:
return f"\nCould not save reviewer output: {exc.strerror or exc}"
return f"\nReviewer output: {path.relative_to(wt)}"


def _review_failure(family: str, exc: Exception) -> tuple[str, str, str]:
lines = str(exc).splitlines()
detail = "\n".join(lines[:3])
fallback_reason = _FALLBACK_REASONS[3]
detail = "\n".join(lines[:1 if isinstance(exc, runners.RunnerMalformedOutput) else 3])
if isinstance(exc, runners.RunnerAuthFailed):
login = "claude auth login" if family == "claude" else "codex login"
detail += f"\nFix: run `{login}`."
fallback_reason = _FALLBACK_REASONS[0]
elif isinstance(exc, runners.RunnerUsageLimit):
detail += "\nFix: wait for the limit to reset or switch this reviewer's account."
fallback_reason = _FALLBACK_REASONS[1]
elif isinstance(exc, runners.RunnerMissing):
return lines[0], detail + f"\nFix: run `{login}`.", _FALLBACK_REASONS[0]
if isinstance(exc, runners.RunnerUsageLimit):
fix = "\nFix: wait for the limit to reset or switch this reviewer's account."
return lines[0], detail + fix, _FALLBACK_REASONS[1]
if isinstance(exc, runners.RunnerMissing):
package = "@anthropic-ai/claude-code" if family == "claude" else "@openai/codex"
detail += f"\nFix: install it with `npm install -g {package}`."
fallback_reason = _FALLBACK_REASONS[2]
return lines[0], detail, fallback_reason
return lines[0], detail + f"\nFix: install it with `npm install -g {package}`.", _FALLBACK_REASONS[2]
return lines[0], detail, _FALLBACK_REASONS[3]


def _independence_message(
Expand Down
10 changes: 5 additions & 5 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ class Readiness:
_read_scope: ContextVar[tuple[float, str | None, bool] | None] = ContextVar("github_reads", default=None)
_api_error_diagnostics: ContextVar[bool] = ContextVar("github_api_error_diagnostics", default=False)
_HTTP_STATUS_RE = re.compile(r"^HTTP/\S+\s+(\d{3})(?:\s+(.*))?$", re.IGNORECASE)
_GITHUB_TOKEN_RE = re.compile(
r"\b(?:github_pat_[A-Za-z0-9_]+|gh[pousr]_[A-Za-z0-9_]{10,})\b"
_CREDENTIAL_TOKEN_RE = re.compile(
r"\b(?:github_pat_[A-Za-z0-9_]+\b|gh[pousr]_[A-Za-z0-9_]{10,}\b|sk-[A-Za-z0-9_-]{8,})"
)


Expand Down Expand Up @@ -220,7 +220,7 @@ def _redact_tokens(value: str, token: str = "") -> str:
value = re.sub(r"(?i)\b(authorization)\s*[:=]\s*"
r"(?:(?:basic|bearer|token)\s+)?[^\s,;]+", r"\1=[REDACTED]", value)
value = re.sub(r"(?i)\bBearer\s+[^\s,;]+", "Bearer [REDACTED]", value)
value = _GITHUB_TOKEN_RE.sub("[REDACTED]", value)
value = _CREDENTIAL_TOKEN_RE.sub("[REDACTED]", value)
value = re.sub(r"(?i)\b(access_token|auth_token|token)\s*[:=]\s*"
r"[^\s,;]+", r"\1=[REDACTED]", value)
value = re.sub(r"(?i)(https?://[^?\s]+)\?[^\s]+", r"\1?[REDACTED]", value)
Expand Down Expand Up @@ -780,7 +780,7 @@ def finding_marker(severity: str, head_sha: str, finding: Finding) -> str:


def _comment_body(f: Finding, head_sha: str, prefix: str = "") -> str:
text = f"{prefix}**{f.severity}: {f.title}**\n\n{f.body}".rstrip()
text = prefix + _CREDENTIAL_TOKEN_RE.sub("[REDACTED]", f"**{f.severity}: {f.title}**\n\n{f.body}").rstrip()
if f.severity in BLOCKING:
return f"{finding_marker(f.severity, head_sha, f)}\n{text}"
return text
Expand Down Expand Up @@ -832,7 +832,7 @@ def _review_body(result: ReviewResult, unplaced: list[Finding], prefix: str = ""
lines.extend(_review_settings_lines(result, include_configured=settings_layout == "current"))
if unplaced:
lines.append("\nFindings without a file location:\n")
lines += [f"- **{f.severity}**: {f.title} — {f.body}".rstrip(" —") for f in unplaced]
lines += [_CREDENTIAL_TOKEN_RE.sub("[REDACTED]", f"- **{f.severity}**: {f.title} — {f.body}".rstrip(" —")) for f in unplaced]
return "\n".join(lines) + _review_transcript(result, legacy_display)


Expand Down
43 changes: 25 additions & 18 deletions src/loopzero/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ def __init__(self, message: str, tail: str = "") -> None:
self.tail = tail


class RunnerMalformedOutput(RunnerBadOutput):
"""The runner returned a payload that could not be parsed as a review."""


class RunnerPromptTooLong(RunnerBadOutput):
"""The provider rejected the prompt for exceeding its context window."""

Expand Down Expand Up @@ -214,33 +218,34 @@ def _claude_payload(envelope: dict) -> object:
return _extract_json_object(str(envelope.get("result", ""))) if payload is None else payload


def parse_review(payload: object, *, family: str, head: str, kind: str, raw: str) -> ReviewResult:
def parse_review(payload: object, *, family: str, head: str, kind: str, raw: str, excerpt: str | None = None) -> ReviewResult:
"""Validate a decoded review object against the findings schema."""
diagnostic = _tail(raw if excerpt is None else excerpt)
if not isinstance(payload, dict):
raise RunnerBadOutput(f"{family}: review is not a JSON object", _tail(raw))
raise RunnerMalformedOutput(f"{family}: review is not a JSON object", diagnostic)
if set(payload) != {"verdict", "findings"}:
raise RunnerBadOutput(f"{family}: review has unexpected or missing keys", _tail(raw))
raise RunnerMalformedOutput(f"{family}: review has unexpected or missing keys", diagnostic)
verdict, items = payload["verdict"], payload["findings"]
if (
not isinstance(verdict, str)
or verdict not in ("approve", "request_changes")
or not isinstance(items, list)
):
raise RunnerBadOutput(f"{family}: review lacks verdict/findings", _tail(raw))
raise RunnerMalformedOutput(f"{family}: review lacks verdict/findings", diagnostic)
findings: list[Finding] = []
for item in items:
required = {"severity", "path", "line", "title", "body"}
if not isinstance(item, dict) or set(item) != required:
raise RunnerBadOutput(f"{family}: finding has unexpected or missing keys", _tail(raw))
raise RunnerMalformedOutput(f"{family}: finding has unexpected or missing keys", diagnostic)
if not isinstance(item["severity"], str) or item["severity"] not in SEVERITIES:
raise RunnerBadOutput(f"{family}: finding has bad severity", _tail(raw))
raise RunnerMalformedOutput(f"{family}: finding has bad severity", diagnostic)
path, line = item["path"], item["line"]
if path is not None and not isinstance(path, str):
raise RunnerBadOutput(f"{family}: finding path is not a string", _tail(raw))
raise RunnerMalformedOutput(f"{family}: finding path is not a string", diagnostic)
if line is not None and (isinstance(line, bool) or not isinstance(line, int)):
raise RunnerBadOutput(f"{family}: finding line is not an integer", _tail(raw))
raise RunnerMalformedOutput(f"{family}: finding line is not an integer", diagnostic)
if not isinstance(item["title"], str) or not isinstance(item["body"], str):
raise RunnerBadOutput(f"{family}: finding title/body must be strings", _tail(raw))
raise RunnerMalformedOutput(f"{family}: finding title/body must be strings", diagnostic)
findings.append(Finding(**item))
if any(f.severity in BLOCKING for f in findings):
verdict = "request_changes"
Expand Down Expand Up @@ -1145,9 +1150,9 @@ def _review_claude(
try:
envelope = _extract_json_object(raw)
except (json.JSONDecodeError, ValueError) as exc:
raise RunnerBadOutput("claude: stdout is not JSON", _tail(raw)) from exc
raise RunnerMalformedOutput("claude: stdout is not JSON", _tail(raw)) from exc
if not isinstance(envelope, dict):
raise RunnerBadOutput("claude: result envelope is not an object", _tail(raw))
raise RunnerMalformedOutput("claude: result envelope is not an object", _tail(raw))
if _claude_envelope_auth_failure(envelope):
raise RunnerAuthFailed(f"claude: CLI is not authenticated\n{_tail(raw)}")
if envelope.get("is_error") and _subscription_exhausted(raw, envelope):
Expand All @@ -1162,15 +1167,15 @@ def _review_claude(
try:
payload = _claude_payload(envelope)
except (json.JSONDecodeError, ValueError) as exc:
raise RunnerBadOutput("claude: result text is not JSON", _tail(raw)) from exc
raise RunnerMalformedOutput("claude: result text is not JSON", _tail(str(envelope.get("result", "")))) from exc
usage = envelope.get("modelUsage")
models = tuple(key for key in usage if isinstance(key, str)) if isinstance(usage, dict) else ()
reported_model = ", ".join(models) or None
provenance = _claude_provenance(envelope, raw)
provenance["requested_settings"] = [{"model": model, "effort": effort}]
provenance["configured_settings"] = [configured]
return replace(
parse_review(payload, family="claude", head=head, kind=kind, raw=raw),
parse_review(payload, family="claude", head=head, kind=kind, raw=raw, excerpt=json.dumps(payload)),
model=reported_model or model, effort=effort,
duration_s=done.duration_s, provenance=provenance,
)
Expand Down Expand Up @@ -1263,18 +1268,20 @@ def _review_codex(
)
final = _codex_final_file(last_file)
if final["status"] not in ("complete", "absent"):
raise RunnerBadOutput("codex: final message file could not be read completely")
raise RunnerMalformedOutput("codex: final message file could not be read completely")
message_bytes = base64.b64decode(final.get("bytes_base64", ""))
try:
message = base64.b64decode(final.get("bytes_base64", "")).decode("utf-8")
message = message_bytes.decode("utf-8")
except UnicodeDecodeError as exc:
raise RunnerBadOutput("codex: final message is not UTF-8") from exc
fragment = _tail(message_bytes.decode(errors="replace"))
raise RunnerMalformedOutput("codex: final message is not UTF-8", fragment) from exc
provenance, raw = _codex_provenance(done.stdout, done.stderr, message, home=home)
if not message.strip():
raise RunnerBadOutput("codex: no final message written", _tail(done.stdout + done.stderr))
try:
payload = _extract_json_object(message)
except (json.JSONDecodeError, ValueError) as exc:
raise RunnerBadOutput("codex: final message is not JSON", _tail(message)) from exc
raise RunnerMalformedOutput("codex: final message is not JSON", _tail(message)) from exc
envelope = _evidence_json(raw)
envelope["configured_settings"] = configured
envelope["cli_version"] = cli_version
Expand All @@ -1285,7 +1292,7 @@ def _review_codex(
provenance["requested_settings"] = [{"model": model, "effort": effort}]
banner_model = _CODEX_MODEL_RE.search(done.stderr)
return replace(
parse_review(payload, family="codex", head=head, kind=kind, raw=raw),
parse_review(payload, family="codex", head=head, kind=kind, raw=raw, excerpt=message),
model=model or (banner_model.group(1) if banner_model else None), effort=effort,
duration_s=done.duration_s,
provenance=provenance,
Expand Down
2 changes: 1 addition & 1 deletion src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ def _require_no_ignored_user_files(wt: Path) -> None:
for path in ignored.split("\0")[:-1]:
if (
(path in {".loopzero/task.md", ".loopzero/checks.json"}
or re.fullmatch(r"\.loopzero/review-[0-9a-f]{12}-(primary|delta)\.json", path))
or re.fullmatch(r"\.loopzero/review(?:er-output)?-[0-9a-f]{12}-(primary|delta)\.json", path))
and not (wt / path).is_symlink()
):
continue
Expand Down
29 changes: 29 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2170,6 +2170,35 @@ def test_review_observes_new_codex_version_in_saved_receipt(
assert result.provenance["cli_version"] == version


@pytest.mark.parametrize("save", [True, False])
def test_review_malformed_fragments_stay_out_of_terminal(wt, gh, fake_bin, monkeypatch, capsys, save):
prepare_review(wt, gh, fake_bin)
envelopes = {family: json.dumps({"unexpected": family * 700}) for family in ("claude", "codex")}

def malformed(family, *, head, kind, **kwargs):
raw = envelopes[family]
cli.runners.parse_review(json.loads(raw), family=family, head=head, kind=kind, raw=raw)

monkeypatch.setattr(cli.runners, "review_with", malformed)
if not save:
def fail(*args):
raise PermissionError("diagnostic write denied")
monkeypatch.setattr(cli, "_write_json_atomically", fail)
code, out, err = run(capsys, "review")
size = len((out + err).encode())
assert size < 650, size
assert code == 4 and "rerun" in err and "wait for the owner" in err
for family in envelopes:
assert f"{family}: review has unexpected or missing keys" in err
assert family * 10 not in err
if save:
path = next((wt / ".loopzero").glob("reviewer-output-*.json"))
assert path.name in err and path.stat().st_mode & 0o777 == 0o600
assert json.loads(path.read_text()) == {family: raw[-2000:] for family, raw in envelopes.items()}
else:
assert "diagnostic write denied" in err


@pytest.mark.parametrize("mixed_authors", [False, True])
def test_review_fails_with_three_line_errors_and_remedies_without_spending_budget(
wt: Path, gh: FakeGh, capsys, monkeypatch, head, mixed_authors
Expand Down
30 changes: 27 additions & 3 deletions tests/test_review_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,16 @@ def arm_published_review(gh, head, body, *, state="COMMENTED"):


def lost_reply(wt, gh, fake_bin, monkeypatch, *, kind, verdict, interrupted=False,
mutate=None, timeout=False):
mutate=None, timeout=False, findings=None):
history = []
if kind == "delta":
history = [rev(head_of(wt), "primary")]
(wt / "feature.py").write_text("print('fixed')\n")
git(wt, "commit", "-qam", "repair")
head = support.prepare_review(wt, gh, fake_bin, history=history, post_id=17,
payload=APPROVE if verdict == 0 else CHANGES)
payload = APPROVE if verdict == 0 else CHANGES
if findings is not None:
payload = {**payload, "findings": findings}
head = support.prepare_review(wt, gh, fake_bin, history=history, post_id=17, payload=payload)
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'))
Expand Down Expand Up @@ -247,6 +249,28 @@ def read(endpoint):
assert len([c for c in gh.calls if "--input" in c]) == 1


def test_repost_recovers_review_with_redacted_findings(wt, gh, fake_bin, monkeypatch, capsys):
title = "Rotate sk-ant-FAKE0123"
findings = [
{"severity": "important", "path": "feature.py", "line": 1,
"title": title, "body": "Remove sk-proj-Fake_only-0123 from settings."},
{"severity": "suggestion", "path": None, "line": None,
"title": "Replace ghp_FAKE0123456789", "body": "See sk-FakeToken0123 in the log."},
]
head = lost_reply(wt, gh, fake_bin, monkeypatch, kind="primary", verdict=5,
interrupted=True, findings=findings)
assert run(capsys, "review")[0] == 130
payload = support.posted_review(gh)
assert "**suggestion**: Replace [REDACTED] — See [REDACTED] in the log." in payload["body"]
comment, = payload["comments"]
assert (comment["path"], comment["line"], comment["side"]) == ("feature.py", 1, "RIGHT")
stable_id = github.finding_id(head, "feature.py", 1, title)
assert comment["body"].splitlines()[0].endswith(f"severity=important head={head} id={stable_id} -->")
assert "**important: Rotate [REDACTED]**\n\nRemove [REDACTED] from settings." in comment["body"]
assert run(capsys, "review", "--repost")[0] == 5
assert_single_publication(gh, fake_bin)


def test_interrupted_explicit_repost_recovers_repost_body(wt, gh, fake_bin, monkeypatch, capsys):
head = lost_reply(wt, gh, fake_bin, monkeypatch, kind="primary", verdict=5, interrupted=True)
original = github._api
Expand Down
6 changes: 4 additions & 2 deletions tests/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -1190,9 +1190,11 @@ def test_unknown_family_and_kind(tmp_path: Path) -> None:
],
)
def test_review_schema_is_strict(fake_bin: Path, tmp_path: Path, finding: dict) -> None:
_fake_codex(fake_bin, json.dumps({"verdict": "request_changes", "findings": [finding]}))
with pytest.raises(RunnerBadOutput):
message = json.dumps({"verdict": "request_changes", "findings": [finding]})
_fake_codex(fake_bin, message)
with pytest.raises(runners.RunnerMalformedOutput) as error:
_review("codex", tmp_path)
assert error.value.tail == message + "\n"


@pytest.mark.parametrize(("has_stderr", "size"), [(True, 0), (True, 3000), (False, 3000)])
Expand Down
Loading
Loading