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
9 changes: 6 additions & 3 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con
prepares recognized uv dependency groups offline in that sandbox and prints
progress before each command, metadata-only stage heartbeats every 30 seconds
(including silent children), and exit code/duration immediately after each stage.
Heartbeats stop on completion or cancellation and never supply a verdict; child
streams remain captured for the existing final report and failing output tail.
Heartbeats stop on completion or cancellation and never supply a verdict.
Local stages drain merged child output and retain a bounded diagnostic tail.
Trusted-base commands remain authoritative;
stale task trees need integration only when prerequisites are missing,
preserving source-preserving queue eligibility for behind branches.
Expand All @@ -94,7 +94,10 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con
newer duplicate exists. If the head commit cannot prove completion, the
pull-list fallback also checks earlier commits of the branch. Failed,
malformed, repeated or truncated history blocks publication, with a limit of
100 pages. An unfinished branch creates or refreshes a draft PR.
100 pages. An unfinished branch creates or refreshes a draft PR. Publication
checks that every effective origin push URL targets the configured GitHub
repository. A leased rewrite also requires the PR head in the task branch's
local history.
4. `review` publishes one native review of the exact authored SHA. The contract's
[review budget](../core/CONTRACT.md#review-budget) owns contributor exclusion,
the PR-wide cap of one primary and one delta across head rewrites, and the
Expand Down
4 changes: 4 additions & 0 deletions scripts/ai-accounts/ai-accounts
Original file line number Diff line number Diff line change
Expand Up @@ -1085,6 +1085,10 @@ def cmd_shim(name: str, args: list[str]) -> int:
dirs = os.environ.get("PATH", "").split(os.pathsep)
shim_dirs = [d for d in dirs if is_shim_dir(d)]
rest = [d for d in dirs if d not in shim_dirs]
if name == "loopzero":
# Codex's transient launcher shims are hidden in the check sandbox.
arg0 = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex") / "tmp/arg0-linux"
rest = [d for d in rest if Path(d).parent != arg0 or not Path(d).name.startswith("codex-arg0")]
real = next((str(c) for d in rest if (c := Path(d or ".") / name).is_file()
and os.access(c, os.X_OK)), None)
if real is None:
Expand Down
52 changes: 51 additions & 1 deletion src/loopzero/_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

from __future__ import annotations

import codecs
import io
import os
import selectors
import signal
import subprocess
import threading
Expand Down Expand Up @@ -104,6 +107,45 @@ def build_env(
return env


def _read_output_tail(proc: subprocess.Popen[str], limit: int, timeout: float) -> str:
stream = proc.stdout
assert stream is not None
decode = io.IncrementalNewlineDecoder(
codecs.getincrementaldecoder(stream.encoding)(errors="replace"), translate=True,
).decode
deadline = time.monotonic() + timeout
suffix = ""
newlines = 0

def append(chunk: str) -> None:
nonlocal suffix, newlines
content = chunk.rstrip("\n")
if content:
suffix = (suffix + "\n" * newlines + content)[-limit:]
newlines = 0
newlines = min(limit, newlines + len(chunk) - len(content))

try:
with selectors.DefaultSelector() as selector:
selector.register(stream, selectors.EVENT_READ)
while True:
remaining = deadline - time.monotonic()
if remaining <= 0 or not selector.select(remaining):
raise subprocess.TimeoutExpired(proc.args, timeout)
chunk = os.read(stream.fileno(), 64 * 1024)
if not chunk:
break
append(decode(chunk))
proc.wait(timeout=max(0, deadline - time.monotonic()))
except subprocess.TimeoutExpired as exc:
append(decode(b"", final=True))
exc.output = (suffix + "\n" * newlines)[-limit:]
raise
append(decode(b"", final=True))
# Check tails strip trailing newlines on success, even when there are many.
return suffix


def run(
argv: Sequence[str],
*,
Expand All @@ -115,6 +157,7 @@ def run(
input: str | None = None,
encoding: str | None = None,
preserve_newlines: bool = False,
tail_chars: int | None = None,
) -> Completed:
"""Run `argv` (never through a shell) with an environment stripped to the allowlist.

Expand All @@ -123,8 +166,12 @@ def run(
`encoding` overrides the parent locale for text I/O; None retains subprocess defaults.
With `preserve_newlines`, decode without newline translation (UTF-8 by default)
and preserve undecodable stdout bytes via surrogateescape.
`tail_chars` bounds merged text output without input, stripping trailing
newlines on completion and retaining them for timeout diagnostics.
Nonzero exit is reported in `Completed.exit_code`; callers decide whether to raise.
"""
if tail_chars is not None and (not merge_output or preserve_newlines or input is not None or tail_chars <= 0):
raise ValueError("bounded tails require merged text output, no input and a positive length")
argv = [str(part) for part in argv]
started = time.monotonic()
raw_encoding = encoding or "utf-8"
Expand All @@ -142,7 +189,10 @@ def run(
start_new_session=os.name == "posix",
) as proc:
try:
stdout, stderr = proc.communicate(stdin, timeout=timeout)
if tail_chars is None:
stdout, stderr = proc.communicate(stdin, timeout=timeout)
else:
stdout, stderr = _read_output_tail(proc, tail_chars, timeout), ""
except BaseException:
if os.name == "posix":
with suppress(ProcessLookupError):
Expand Down
19 changes: 18 additions & 1 deletion src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,18 @@ def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT) -> str:
return done.stdout.strip()


def _require_push_target(wt: Path, repo: str) -> None:
urls = _git(wt, "remote", "get-url", "--push", "--all", "origin").splitlines()
github_url = re.compile(
r"(?:https://(?:[a-z0-9._~%:+-]+@)?github\.com(?::443)?/"
r"|git@github\.com:|ssh://git@github\.com(?::22)?/|ssh://git@ssh\.github\.com:443/)"
+ re.escape(repo) + r"(?:\.git)?/?",
re.IGNORECASE | re.ASCII,
)
if not urls or any(not github_url.fullmatch(url) for url in urls):
raise CliError(f"origin push URL does not target {repo}; correct the Git remote before running pr")


def _git_push(wt: Path, args: list[str], *, force_lease: bool) -> None:
done = _proc.run(["git", *args], cwd=wt, env_allowlist=worktree.GIT_ENV,
extra_env={"LC_ALL": "C"}, timeout=PUSH_TIMEOUT)
Expand Down Expand Up @@ -678,7 +690,6 @@ def cmd_pr(args: argparse.Namespace) -> int:
force_lease = False
push = ["push", "-u", "origin"]
if pr is not None and pr.state == "OPEN":
# Only rewrite history this worktree has seen; an unknown remote head is someone else's.
known = _proc.run(["git", "cat-file", "-e", f"{pr.head_sha}^{{commit}}"], cwd=wt,
env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT)
if known.exit_code != 0:
Expand All @@ -687,8 +698,14 @@ def cmd_pr(args: argparse.Namespace) -> int:
)
force_lease = not _is_ancestor(wt, pr.head_sha, head)
if force_lease:
previous_heads = _git(wt, "reflog", "show", "--format=%H", f"refs/heads/{branch}").splitlines()
if not any(_is_ancestor(wt, pr.head_sha, previous) for previous in previous_heads):
raise CliError(
f"PR head {pr.head_sha[:12]} is absent from this task branch's history; integrate it first"
)
push.extend(("--porcelain", f"--force-with-lease={branch}:{pr.head_sha}"))
push.append(branch)
_require_push_target(wt, config.repo)
_git_push(wt, push, force_lease=force_lease)
if pr is not None and pr.state == "OPEN":
with _lock_task_state(wt):
Expand Down
1 change: 1 addition & 0 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,7 @@ def _run_one(
env_allowlist=config.env_allowlist,
timeout=timeout,
merge_output=True,
tail_chars=CHECK_TAIL_BYTES,
)
except _proc.ProcTimeout as exc:
return CheckResult(command, TIMEOUT_EXIT, timeout,
Expand Down
7 changes: 5 additions & 2 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,10 @@ def test_shim_prefers_verified_codex_only_for_loopzero(helper, tmp_path, monkeyp
codex = pin / 'codex'
codex.write_text('#!/bin/sh\nexit 0\n')
codex.chmod(0o755 if pin_state != 'nonexecutable' else 0o644)
monkeypatch.setenv('PATH', f'{shims}:{binaries}')
codex_home = tmp_path / 'codex-home'
arg0 = codex_home / 'tmp/arg0-linux/codex-arg0ABC123'
monkeypatch.setenv('CODEX_HOME', str(codex_home))
monkeypatch.setenv('PATH', f'{shims}:{arg0}:{binaries}')
monkeypatch.setattr(helper.sys, 'argv', [str(shims / name)])
calls = []
monkeypatch.setattr(helper.os, 'execve', lambda *args: calls.append(args))
Expand All @@ -471,7 +474,7 @@ def test_shim_prefers_verified_codex_only_for_loopzero(helper, tmp_path, monkeyp
expected.insert(0, str(pin))
assert env['PATH'].split(helper.os.pathsep) == expected
else:
assert env['PATH'] == f'{shims}:{binaries}'
assert env['PATH'] == f'{shims}:{arg0}:{binaries}'


@pytest.mark.parametrize('provider,email,shown', [
Expand Down
39 changes: 30 additions & 9 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,14 @@ def repo(git_seed: Path, tmp_path: Path, fake_tool, monkeypatch, request: pytest
shutil.copytree(git_seed / seed_checkout, checkout)
origin = shutil.copytree(git_seed / "origin.git", tmp_path / "origin.git")
git(checkout, "remote", "set-url", "origin", str(origin))
run_command = github.run
run_command, git_command = github.run, cli._git

def local_push_url(cwd, *args, **kwargs):
output = git_command(cwd, *args, **kwargs)
if args == ("remote", "get-url", "--push", "--all", "origin"):
return "\n".join(f"https://github.com/{REPO}.git" if url == str(origin) else url
for url in output.splitlines())
return output

def local_transport(argv, **kwargs):
if argv[0] == "git" and "push" in argv:
Expand All @@ -120,6 +127,7 @@ def local_transport(argv, **kwargs):
return run_command(argv, **kwargs)

monkeypatch.setattr(github, "run", local_transport)
monkeypatch.setattr(cli, "_git", local_push_url)
fake_tool("bwrap", FAKE_BWRAP.format(log=tmp_path / "bwrap.argv"))
return checkout

Expand Down Expand Up @@ -1194,16 +1202,20 @@ def test_pr_aborts_on_missing_remote_head(wt, gh, fake_tool, tmp_path, capsys):
assert all("--method" not in call["argv"] for call in gh.calls)


@pytest.mark.parametrize("hook_fails", [False, True])
@pytest.mark.parametrize("case", ["rewrite", "hook-fails", "wrong-destination"])
def test_pr_uses_lease_for_rewritten_open_pr(
wt: Path, repo: Path, gh: FakeGh, fake_tool, tmp_path: Path, capsys, hook_fails: bool
wt: Path, repo: Path, gh: FakeGh, fake_tool, tmp_path: Path, capsys, case: str
) -> None:
old = head_of(wt)
git(wt, "push", "-q", "-u", "origin", "lz/t1")
git(wt, "reset", "-q", "--soft", "HEAD~1")
git(wt, "commit", "-q", "-m", "rebased feature")
head = head_of(wt)
if hook_fails:
origin, other = repo.parent / "origin.git", tmp_path / "other.git"
if case == "wrong-destination":
shutil.copytree(origin, other)
git(wt, "remote", "set-url", "--push", "origin", str(other))
if case == "hook-fails":
hook = fake_tool("pre-push", "echo 'lint failed in widget.py' >&2\nexit 1\n")
git(wt, "config", "core.hooksPath", str(hook.parent))
pushes = trace_pushes(fake_tool, tmp_path)
Expand All @@ -1212,19 +1224,25 @@ def test_pr_uses_lease_for_rewritten_open_pr(

code, out, err = run(capsys, "pr")

if hook_fails:
if case == "wrong-destination":
assert (code, out) == (1, "") and "origin push URL does not target" in err
assert not pushes.exists()
assert all(git(remote, "rev-parse", "refs/heads/lz/t1").strip() == old for remote in (origin, other))
return
if case == "hook-fails":
assert (code, out) == (1, "") and "lint failed in widget.py" in err
assert "remote moved" not in err and all("PATCH" not in call["argv"] for call in gh.calls)
else:
assert (code, out, err) == (0, URL + "\n", "")
assert pushes.read_text().strip() == (
f"push -u origin --porcelain --force-with-lease=lz/t1:{old} lz/t1"
)
assert git(repo.parent / "origin.git", "rev-parse", "refs/heads/lz/t1").strip() == (old if hook_fails else head)
assert git(origin, "rev-parse", "refs/heads/lz/t1").strip() == (old if case == "hook-fails" else head)


@pytest.mark.parametrize("shared_object", [False, True])
def test_pr_reports_rejected_lease_without_overwriting_remote(
wt: Path, repo: Path, gh: FakeGh, tmp_path: Path, capsys
wt: Path, repo: Path, gh: FakeGh, tmp_path: Path, capsys, shared_object: bool
) -> None:
old = head_of(wt)
origin = repo.parent / "origin.git"
Expand All @@ -1237,11 +1255,14 @@ def test_pr_reports_rejected_lease_without_overwriting_remote(
commit_file(mover, "remote.txt", "moved\n", "remote move")
git(mover, "push", "-q", "origin", "lz/t1")
moved = git(origin, "rev-parse", "refs/heads/lz/t1").strip()
gh.respond_pr_list([pr_json(headRefOid=old)])
if shared_object:
git(repo, "fetch", "-q", "origin", "lz/t1")
gh.respond_pr_list([pr_json(headRefOid=moved if shared_object else old)])

code, out, err = run(capsys, "pr")

assert code == 1 and out == "" and "remote moved" in err
diagnostic = "absent from this task branch's history" if shared_object else "remote moved"
assert code == 1 and out == "" and diagnostic in err
assert git(origin, "rev-parse", "refs/heads/lz/t1").strip() == moved


Expand Down
59 changes: 43 additions & 16 deletions tests/test_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
import json
import os
import resource
import shlex
import shutil
import signal
import subprocess
import sys
import tempfile
import tracemalloc
import traceback
from contextlib import ExitStack
from dataclasses import replace
Expand Down Expand Up @@ -110,9 +112,10 @@ def test_report_fails_when_head_changes_during_run(git_repo, bwrap_log):

@pytest.mark.parametrize("command,exit_code,line_count,start,end", [
("for i in $(seq 1 50); do echo $i; done; echo err >&2", 0, 40, "12", "err"),
("""python3 -c 'print("x" * 16777216 + " Ω end")'""", 0, 1, "x", " Ω end"),
("""python3 -c 'print("x" * 20000 + " Ω end")'""", 0, 1, "x", " Ω end"),
("""python3 -c 'print("terminal line" + "\\n" * 20_000)'""", 0, 1, "terminal line", "terminal line"),
("./" * 8_200 + "absent/file", 1, 1, "", "otherwise restore the required file."),
], ids=["lines", "oversized-line", "missing-file"])
], ids=["lines", "oversized-line", "trailing-newlines", "missing-file"])
def test_tail_merges_streams_and_truncates(git_repo, bwrap_log, command, exit_code, line_count, start, end):
(result,) = sandbox.run_checks(make_config(checks=(command,)), git_repo).results
lines = result.tail.splitlines()
Expand Down Expand Up @@ -233,26 +236,50 @@ def test_temp_parent_cannot_be_exposed(git_repo, bwrap_log):


def inject_check_timeout(monkeypatch, output, before_timeout=None):
communicate = subprocess.Popen.communicate
def read_output_tail(process, limit, timeout):
if before_timeout is not None:
before_timeout()
raise subprocess.TimeoutExpired(process.args, timeout, output=output[-limit:])

def communicate_with_timeout(process, input=None, timeout=None):
if tuple(process.args[-6:-1]) == sandbox.CHECK_SHELL:
if before_timeout is not None:
before_timeout()
raise subprocess.TimeoutExpired(process.args, timeout, output=output)
return communicate(process, input, timeout)
monkeypatch.setattr(sandbox._proc, "_read_output_tail", read_output_tail)

monkeypatch.setattr(subprocess.Popen, "communicate", communicate_with_timeout)

def test_verbose_stage_bounds_parent_memory(git_repo):
command = shlex.join([sys.executable, "-c", """
import os
import sys

def test_timeout_is_recorded_not_raised(git_repo, bwrap_log, monkeypatch):
inject_check_timeout(monkeypatch, b"x" * 20_000 + b"partial")
block = b"x" * (1024 * 1024)
for _ in range(50):
sys.stdout.buffer.write(block)
sys.stdout.flush()
os.write(1, b"\\r\\nlast stdout\\r\\n")
os.write(2, "final Ω diagnostic\\r\\n".encode())
sys.exit(7)
"""])
tracemalloc.start()
try:
tracemalloc.reset_peak()
baseline, _ = tracemalloc.get_traced_memory()
result = sandbox._run_one(make_config(), git_repo, [], command, 30)
_, peak = tracemalloc.get_traced_memory()
finally:
tracemalloc.stop()
assert result.exit_code == 7
assert result.tail.endswith("\nlast stdout\nfinal Ω diagnostic")
assert len(result.tail.encode()) == 16 * 1024
assert peak - baseline < 4 * 1024 * 1024


def test_timeout_is_recorded_with_drained_output(git_repo, bwrap_log):
command = "printf '%20000s\\n' ''; echo last diagnostic >&2; exec sleep 30"
report = sandbox.run_checks(
make_config(checks=("echo partial", "echo after")), git_repo, timeout=0.3
make_config(checks=(command, "echo after")), git_repo, timeout=1
)
(first,) = report.results
assert (first.exit_code, len(first.tail.encode("utf-8"))) == (sandbox.TIMEOUT_EXIT, 16 * 1024)
assert "partial\n[loopzero] timed out" in first.tail and not report.ok
(result,) = report.results
assert result.exit_code == sandbox.TIMEOUT_EXIT and not report.ok
assert result.tail.endswith("\nlast diagnostic\n\n[loopzero] timed out after 1s")
assert len(result.tail.encode()) == 16 * 1024


def test_configured_resource_limits_are_converted_to_bytes(git_repo, bwrap_log, monkeypatch):
Expand Down
Loading