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 @@ -57,7 +57,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 @@ -1039,7 +1039,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 @@ -1073,7 +1073,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 @@ -1095,33 +1095,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
49 changes: 28 additions & 21 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 @@ -533,7 +538,7 @@ def _repository_skill_paths(cwd: Path) -> set[str]:
def _claude_provenance(envelope: dict, raw: str) -> dict[str, object]:
required = ("session_id", "usage", "total_cost_usd", "duration_api_ms")
if any(name not in envelope for name in required):
raise RunnerBadOutput("claude: result envelope lacks provenance", _tail(raw))
raise RunnerMalformedOutput("claude: result envelope lacks provenance", _tail(raw))
session_id = envelope["session_id"]
usage = envelope["usage"]
cost = envelope["total_cost_usd"]
Expand All @@ -547,7 +552,7 @@ def _claude_provenance(envelope: dict, raw: str) -> dict[str, object]:
or isinstance(duration, bool)
or not isinstance(duration, (int, float))
):
raise RunnerBadOutput("claude: result envelope has invalid provenance", _tail(raw))
raise RunnerMalformedOutput("claude: result envelope has invalid provenance", _tail(raw))
return {
"family": "claude",
"session_id": session_id,
Expand Down Expand Up @@ -1079,7 +1084,7 @@ def _codex_provenance(
else None
)
if not session_id or not isinstance(usage, dict):
raise RunnerBadOutput(
raise RunnerMalformedOutput(
"codex: execution output lacks session/token provenance", _tail(stdout + stderr)
)
clean_stderr = re.sub(r"\x1b\[[0-9;]*m", "", stderr)
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,7 +1167,7 @@ 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(raw)) 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
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))
raise RunnerMalformedOutput("codex: no final message written", _tail(done.stdout + done.stderr))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Codex runtime diagnostics reclassified as malformed lose their terminal line

codex: no final message written and codex: execution output lacks session/token provenance (line 1090) carry the tail of codex stdout+stderr. That is the runtime event stream, not a rejected review message. These are now RunnerMalformedOutput, so _review_failure keeps only the first line, and the stderr/event excerpt that was shown before is visible only in the private file. The task says runtime diagnostics keep their existing output. If codex exits 0 after a turn/stream failure, the operator loses the inline hint. Smallest fix: keep these two as plain RunnerBadOutput. Reserve RunnerMalformedOutput for payloads the model produced (parse_review, final message not JSON/UTF-8, claude result/envelope parsing).

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
29 changes: 29 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,35 @@ def expect_cli(capsys, exit_code, *argv, stdout=None, stderr=None, stdout_contai
return out, err


@pytest.mark.parametrize("save", [True, False])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

important: Change pushes tests over the size-budget cap, so the shared gate fails

scripts/size_budget.sh sets TESTS_CAP=13850. It fails when the test line count is over the cap and has grown against the base. The task notes say the merged head has 13,888 test lines, and this diff adds 37 test lines, so loopzero check/CI fails on this branch. The size-budget check is part of acceptance, so this cannot merge as is. Smallest fix: make the new tests shorter. For example, drop the parametrized save split into one test with two compact assertions. Or fold test_codex_schema_error_keeps_the_rejected_message into the existing strict-schema test. Do not raise the cap without a justification.

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


# --- start / check --------------------------------------------------------------------


Expand Down
6 changes: 4 additions & 2 deletions tests/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -1212,9 +1212,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