Skip to content
3 changes: 3 additions & 0 deletions core/skills/diagnose/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ Rank competing hypotheses from evidence. Use discriminating experiments and
predicted observations to establish cause; correlation or symptom disappearance
is insufficient. For intermittent failures, use enough observations to distinguish
improvement from chance. Aggregate available logs before adding instrumentation.
After one retry of a check that reports `runner failure, not a check result`,
if the retry also reports runner failure, stop retrying. Report the runner exit
code, log path and host for diagnosis in the same turn.
When the same check fails twice, before any requeue or rerun, diff the last
green run against the first red one: runner or host, environment (ports, env
vars, services, labels) and code. A host or runner change that is live ahead of
Expand Down
20 changes: 12 additions & 8 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -543,9 +543,11 @@ ASCII escaping and compact separators (`,` and `:`). Stdout must contain exactly
one JSON object echoing worktree, head, base, command, network and env_sha256, plus
`exit_code` (integer), `duration_s` (finite nonnegative number), `not_started`
(boolean), and `tail` (string). Env values must not be echoed. Diagnostics belong
on stderr. Missing, extra, duplicate, malformed or mismatched fields and runner
process failures fail the stage closed. Runner timeouts report exit code 124
and the measured elapsed duration. `not_started=true` requires exit_code=0,
on stderr. A valid reported stage failure is authoritative even if the runner
also exits nonzero. Missing, extra, duplicate, malformed or mismatched fields
and interruption before a complete result are runner failures. Check preserves
the prior receipt, returns the runner status (124 for a supervisor timeout), and
does not publish a stage verdict. A receipt is eligible only for its own HEAD. `not_started=true` requires exit_code=0,

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: Unwrapped long lines in the rewritten paragraphs

The new text ...does not publish a stage verdict. A receipt is eligible only for its own HEAD. \not_started=true` requires exit_code=0,andfor reuse. Delegated results are published only after the check completes. A checkpoint cannot replace...` go well past the wrap width the rest of the file uses. Rewrap these paragraphs to keep the diffs reviewable.

duration_s=0 and empty tail, and permits only local fallback through bwrap.

The runner may read `worktree` as data to execute the exact clean head, including
Expand All @@ -557,11 +559,13 @@ the authoritative `checks.json` receipt. Checks lock the task state directory
through execution and receipt publication. A waiter can reuse a newly published
passing receipt when HEAD, settings and declared inputs match. Writers recheck
HEAD and atomically replace the receipt from a synced sibling temporary file.
Successful keyed stages are checkpointed in the same receipt for reuse.
A successful stage checkpoint preserves a clean pass for the same head,
settings and commands. A failed stage replaces an existing receipt immediately.
Final worktree validation is required before publishing a pass. Runners cannot
select stages or mint receipts. Stage admission
Successful local keyed stages are checkpointed in the same receipt for reuse.
Their checkpoints preserve a clean pass for the same head, settings and
commands. A reported failed stage replaces the receipt immediately. Successful
delegated stages are checkpointed if the coordinator is interrupted, and
discarded if the runner fails. Final worktree validation is required before
publishing a pass. Runners cannot select stages
or mint receipts. Stage admission
belongs to the runner: the outer `loopzero check`
must not hold a heavy slot when a runner is configured. Without a runner, the
existing local execution path is unchanged.
Expand Down
2 changes: 1 addition & 1 deletion src/loopzero/_cli_entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ def main(argv: list[str] | None = None) -> int:
args = parse_args(build_parser(), argv)
from loopzero.cli import _run

return _run(args)
return _run(args, console=True)
8 changes: 8 additions & 0 deletions src/loopzero/_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ def unwind_on_sigterm():
raise


def exit_status(code: int) -> int:
if code < 0:
if -code not in (signal.SIGKILL, signal.SIGSTOP):
signal.signal(-code, signal.SIG_DFL)
signal.raise_signal(-code)
return code


@contextmanager
def defer_sigterm():
"""Finish a private directory operation before unwinding."""
Expand Down
7 changes: 4 additions & 3 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1932,7 +1932,7 @@ def main(argv: list[str] | None = None) -> int:
return _run(parse_args(build_parser(), argv))


def _run(args: argparse.Namespace) -> int:
def _run(args: argparse.Namespace, *, console: bool = False) -> int:
try:
with _proc.unwind_on_sigterm():
return globals()[f"cmd_{args.command}"](args)
Expand All @@ -1946,7 +1946,8 @@ def _run(args: argparse.Namespace) -> int:
message = str(exc) if isinstance(exc, ReviewersUnavailable) else _one_line(exc)
prefix = "unexpected response: " if isinstance(exc, UNEXPECTED) else ""
print(f"loopzero {args.command}: {prefix}{message}", file=sys.stderr)
return 1
code = exc.exit_code if isinstance(exc, sandbox.StageRunnerFailure) else 1
return _proc.exit_status(code) if console else code
except KeyboardInterrupt:
print(f"loopzero {args.command}: interrupted", file=sys.stderr)
return 130
Expand All @@ -1957,4 +1958,4 @@ def _one_line(exc: BaseException) -> str:


if __name__ == "__main__":
sys.exit(_run(_module_args))
sys.exit(_run(_module_args, console=True))
109 changes: 60 additions & 49 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ class SandboxUnavailable(LoopZeroError):
"""bubblewrap is missing or cannot create a sandbox on this host."""


class StageRunnerFailure(LoopZeroError):
def __init__(self, exit_code: int, detail: str):
super().__init__(f"runner failure, not a check result: {detail}")
self.exit_code = exit_code


@contextmanager
def _private_directories():
with ExitStack() as stack:
Expand Down Expand Up @@ -109,7 +115,8 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO
git_dir = _git_dir(config, worktree, "--git-dir")

_validate_scratch(config.scratch, worktree, common_dir, git_dir)
with _proc.unwind_on_sigterm(), _private_directories() as stack:
with (_proc.unwind_on_sigterm(), _stage_checkpoints(checkpoint, bool(config.check_runner)) as save,
_private_directories() as stack):
prefix = []
if not config.check_runner:
home = _enter_private_directory(stack, "loopzero-home-")
Expand Down Expand Up @@ -148,47 +155,54 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO
result = replace(result, input_key=key)
if ordinal > len(preparations) or result.exit_code:
results.append(result)
_checkpoint_stage(
checkpoint, CheckReport(head, dirty, tuple(results), settings_sha256),
previous, commands[ordinal:],
)
save(CheckReport(head, dirty, tuple(results), settings_sha256), previous, commands[ordinal:])
if status:
status(f"stage {ordinal}/{len(commands)}: exit {result.exit_code} "
f"({result.duration_s:.1f}s)")
if result.exit_code != 0:
break
final_head = _git(config, worktree, "rev-parse", "HEAD").strip()
final_dirty = bool(_git(config, worktree, "status", "--porcelain").strip())
if (final_head, final_dirty) != (head, dirty):
results.append(CheckResult("<worktree changed during run>", 1, 0.0, (
f"HEAD before: {head}; HEAD after: {final_head}; "
f"dirty before: {dirty}; dirty after: {final_dirty}"
)))
dirty = True
# A runner upgrade during execution makes the resulting receipt unverified.
settings_sha256 = (
settings_sha256 if not config.check_runner
or settings_sha256 == settings_fingerprint(config) else None
)
return CheckReport(head=head, dirty=dirty, results=tuple(results), settings_sha256=settings_sha256)
final_head = _git(config, worktree, "rev-parse", "HEAD").strip()
final_dirty = bool(_git(config, worktree, "status", "--porcelain").strip())
if (final_head, final_dirty) != (head, dirty):
results.append(CheckResult("<worktree changed during run>", 1, 0.0, (
f"HEAD before: {head}; HEAD after: {final_head}; "
f"dirty before: {dirty}; dirty after: {final_dirty}"
)))
dirty = True
# A runner upgrade during execution makes the resulting receipt unverified.
settings_sha256 = (
settings_sha256 if not config.check_runner
or settings_sha256 == settings_fingerprint(config) else None
)
return CheckReport(head=head, dirty=dirty, results=tuple(results), settings_sha256=settings_sha256)


INCOMPLETE_CHECK_COMMAND = "<checks incomplete>"
INCOMPLETE_CHECK = CheckResult(INCOMPLETE_CHECK_COMMAND, 1, 0.0, "")


def _checkpoint_stage(checkpoint: Callable[[CheckReport], None] | None,
report: CheckReport, previous: dict[str, CheckResult],
remaining: tuple[str, ...]) -> None:
if checkpoint is None:
return
stage = report.results[-1]
if stage.exit_code:
checkpoint(report)
elif stage.input_key:
# Even the last stage leaves a nonpassing receipt until final validation.
unvisited = tuple(previous[command] for command in remaining if command in previous)
checkpoint(replace(report, results=(*report.results, *unvisited, INCOMPLETE_CHECK)))
@contextmanager
def _stage_checkpoints(checkpoint: Callable[[CheckReport], None] | None, delegated: bool):
pending = None

def save(report: CheckReport, previous: dict[str, CheckResult], remaining: tuple[str, ...]) -> None:
nonlocal pending
stage = report.results[-1]
if not stage.exit_code:
if not stage.input_key:
return
unvisited = (previous[command] for command in remaining if command in previous)
report = replace(report, results=(*report.results, *unvisited, INCOMPLETE_CHECK))
pending = report if delegated and not stage.exit_code else None
if pending is None:
checkpoint(report)

try:
yield save if checkpoint is not None else lambda *_: None
except (KeyboardInterrupt, _proc.Terminated):
if pending is not None:
checkpoint(pending)
raise


def _previous(config: Config, worktree: Path, settings_sha256: str) -> dict[str, CheckResult]:
Expand Down Expand Up @@ -622,7 +636,7 @@ def _runner_executable(config: Config) -> str | None:
return executable if Path(executable).is_absolute() else shutil.which(executable)


def _stage_frame(stdout: str, binding: dict) -> dict:
def _stage_frame(stdout: str, binding: dict, runner_exit: int) -> dict:
frame = json.loads(stdout, object_pairs_hook=_unique_fields)
if (not isinstance(frame, dict)
or set(frame) != {*binding, "exit_code", "duration_s", "not_started", "tail"}
Expand All @@ -632,7 +646,8 @@ def _stage_frame(stdout: str, binding: dict) -> dict:
or type(frame["duration_s"]) not in (int, float)
or not math.isfinite(frame["duration_s"]) or frame["duration_s"] < 0
or type(frame["not_started"]) is not bool
or not isinstance(frame["tail"], str)):
or not isinstance(frame["tail"], str)
or (runner_exit and not frame["exit_code"])):
raise ValueError("invalid or mismatched stage result")
return frame

Expand All @@ -644,6 +659,7 @@ def _dispatch_one(
binding = {"worktree": str(worktree.resolve()), "head": head, "base": base, "command": command, "network": config.network,
"env_sha256": hashlib.sha256(json.dumps(
env, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()}
runner_exit, stderr = 0, ""
try:
if not _stage_unchanged(config, worktree, head):
raise ValueError("Worktree changed before stage")
Expand All @@ -662,32 +678,27 @@ def _dispatch_one(
for path in {value, *value.split(":")}
if Path(path).is_absolute() or ".." in Path(path).parts):
raise ValueError("Stage runner references task worktree")
done = _proc.run(argv, cwd=cwd, env_allowlist=config.env_allowlist, timeout=timeout,
input=json.dumps({**binding, "env": env}), encoding="utf-8")
if done.exit_code:
stderr = _proc.tail(_redact_check_output(config, done.stderr))[-2000:]
detail = f"Stage runner failed: process exit {done.exit_code}"
return CheckResult(command, done.exit_code, done.duration_s,
f"{detail}\n{stderr}".rstrip())
frame = _stage_frame(done.stdout, binding)
try:
done = _proc.run(argv, cwd=cwd, env_allowlist=config.env_allowlist, timeout=timeout,
input=json.dumps({**binding, "env": env}), encoding="utf-8")
stdout, stderr, runner_exit = done.stdout, done.stderr, done.exit_code
except _proc.ProcTimeout as exc:
stdout, stderr, runner_exit = exc.stdout, f"timed out after {timeout:g}s\n{exc.stderr}", TIMEOUT_EXIT
frame = _stage_frame(stdout, binding, runner_exit)
if not _stage_unchanged(config, worktree, head):
raise ValueError("Worktree changed after stage")

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: Worktree drift is now reported as a runner failure

Before this change, a clean exit 0 runner followed by a worktree change produced a dirty CheckReport, and _save_report discarded it. Now it raises StageRunnerFailure(1, 'Worktree changed after stage') (the same applies to 'before stage' and 'before fallback'). The CLI prints runner failure, not a check result. The new diagnose-skill guidance tells agents to retry once and then report the runner exit, log path and host. Here the cause is the agent's own worktree mutation, not the runner or host, so that guidance sends diagnosis the wrong way. Keeping the prior receipt is fine. Consider raising a distinct message or exception for drift, e.g. a WorktreeError that _run already maps, so it isn't labelled a runner failure.

if frame["not_started"]:
if frame["exit_code"] or frame["duration_s"] or frame["tail"]:
raise ValueError("inconsistent not-started result")
if not _stage_unchanged(config, worktree, head):
raise ValueError("Worktree changed before fallback")
local = run_checks(replace(config, check_runner=(), checks=(command,), inputs={}),
worktree, timeout=timeout, _resolved=True)
if local.dirty:
raise ValueError("Local fallback failed")
return local.results[-1]
return CheckResult(command, frame["exit_code"], frame["duration_s"],
_check_tail(frame["tail"], config))
except _proc.ProcTimeout as exc:
return CheckResult(command, TIMEOUT_EXIT,
exc.duration_s if exc.duration_s is not None else timeout,
_check_tail(exc.stdout, config, suffix=f"\n[loopzero] timed out after {timeout:g}s"))
except (LoopZeroError, ValueError, TypeError, OverflowError, RecursionError, OSError) as exc:
detail = _redact_check_output(config, str(exc))
return CheckResult(command, 1, 0.0, _check_tail(f"Stage runner failed: {detail}"))
if runner_exit:
tail = _proc.tail(_redact_check_output(config, stderr))[-2000:]
raise StageRunnerFailure(runner_exit, f"process exit {runner_exit}\n{tail}".rstrip()) from exc
raise StageRunnerFailure(1, _check_tail(str(exc), config)) from exc
52 changes: 52 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,58 @@ def test_malformed_live_markers_do_not_mask_check_verdict(
assert json.loads((wt / ".loopzero/checks.json").read_text())["results"][0]["exit_code"] == 0


@pytest.mark.parametrize("runner_exit, new_head", [(75, False), (124, False), (-15, True), (-9, False), (0, False)])
def test_check_receipt_requires_stage_result(wt, gh, monkeypatch, capsys, head, runner_exit, new_head):
assert run(capsys, "check")[0] == 0
receipt = wt / ".loopzero/checks.json"
previous = receipt.read_bytes(), receipt.stat().st_mtime_ns
if new_head:
git(wt, "commit", "--allow-empty", "-m", "New candidate")
current = git(wt, "rev-parse", "HEAD").strip()
calls = list(gh.calls)
context = cli._context
script = f"""
import json, os, sys
frame = json.load(sys.stdin)
code = {runner_exit}
if frame["command"] == "echo ok":
code = 0
stage_exit = 0
else:
stage_exit = 7
if code < 0:
print('{{"exit_code":', flush=True)
os.kill(os.getpid(), -code)
if code:
sys.exit(code)
del frame["env"]
print(json.dumps(dict(frame, exit_code=stage_exit, duration_s=0, tail="", not_started=False)))
"""

def with_runner(*args, **kwargs):
worktree, settings = context(*args, **kwargs)
return worktree, replace(settings, check_runner=(sys.executable, "-c", script),
inputs={"echo ok": ("feature.py",)})

monkeypatch.setattr(cli, "_context", with_runner)
code, out, err = run(capsys, "check")
if runner_exit:
assert code == runner_exit
assert f"runner failure, not a check result: process exit {runner_exit}" in err
assert "PASS" not in out and "FAIL" not in out
assert (receipt.read_bytes(), receipt.stat().st_mtime_ns) == previous
assert gh.calls == calls
else:
assert code == 1 and out.endswith("FAIL\n")
assert cli._load_report(wt).results[-1].exit_code == 7
assert (receipt.read_bytes(), receipt.stat().st_mtime_ns) != previous
if new_head:
arm_approved_pr_with_check_result(gh, current, wt, "success", readiness={"local_exit": None})
out, _ = expect_cli(capsys, 1, "ready")
assert f"check receipt is for {head[:12]}" in out
assert all(c["argv"][:2] != ["pr", "ready"] for c in gh.calls)


@pytest.mark.parametrize("receipt", ["saved", "head moved", "write failed"])
def test_check_bounds_large_failure_and_preserves_receipt(wt, head, capsys, monkeypatch, receipt):
tail = 'TEST_FAILURES={"detail":"' + "é" * 7500 + '","error":"Failed to fetch package"}\n'
Expand Down
Loading
Loading