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
7 changes: 4 additions & 3 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
from loopzero.runners import review_settings
from loopzero.types import BLOCKING, Finding, ReviewResult

GH_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GH_TOKEN", "GITHUB_TOKEN", "GH_HOST")
GH_BASE_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GH_HOST")
GH_ENV = (*GH_BASE_ENV, "GH_TOKEN", "GITHUB_TOKEN")
APP_TOKEN_HELPER = Path.home() / ".config/loopzero/app-token"
_app_token_cache = ("", 0.0)
MISSING_REVIEW_REASON = "no review recorded for the current head"
Expand Down Expand Up @@ -297,7 +298,7 @@ def app_token() -> str:
return ""
minted = _app_token_clock() # before minting so a suspend mid-call ages the token
try:
result = run([str(APP_TOKEN_HELPER)], cwd=Path("/"), env_allowlist=GH_ENV, timeout=_read_timeout(10))
result = run([str(APP_TOKEN_HELPER)], cwd=Path("/"), env_allowlist=GH_BASE_ENV, timeout=_read_timeout(10))
except (ToolMissing, ProcTimeout, ReadDeadline, OSError):
return ""
if result.exit_code or not result.stdout.strip():
Expand Down Expand Up @@ -1463,7 +1464,7 @@ def delete_remote_branch(repo: str, branch: str, expected_head: str) -> bool:
env = {"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "GIT_TERMINAL_PROMPT": "0"}
with tempfile.TemporaryDirectory(prefix="loopzero-cleanup-") as scratch:
init = ("git", "init", "--bare", "--template=")
done = run(init, cwd=scratch, env_allowlist=GH_ENV, extra_env=env, timeout=120)
done = run(init, cwd=scratch, env_allowlist=GH_BASE_ENV, extra_env=env, timeout=120)
if done.exit_code != 0:
raise GhError(init, done.stderr or done.stdout)
done = run(argv, cwd=scratch, env_allowlist=GH_ENV, extra_env=env, timeout=120)
Expand Down
57 changes: 21 additions & 36 deletions tests/test_architecture_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,43 +13,35 @@
SCRIPT = Path(__file__).resolve().parents[1] / "scripts/check_architecture_docs.py"


def prepare(repo):
@pytest.fixture
def base(git_repo):
for name in ("docs/ARCHITECTURE.md", "docs/README.md", "README.md", "AGENTS.md",
"core/CONTRACT.md"):
path = repo / name
path = git_repo / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("# Current\n")
git(repo, "add", ".")
git(repo, "commit", "-m", "architecture base")
return git(repo, "rev-parse", "HEAD").strip()
git(git_repo, "add", ".")
git(git_repo, "commit", "-m", "architecture base")
return git(git_repo, "rev-parse", "HEAD").strip()


def run(repo, base, *args):
return subprocess.run([sys.executable, str(SCRIPT), base, *args], cwd=repo,
text=True, capture_output=True, check=False)


@pytest.mark.skipif(sys.platform != "linux", reason="requires raw pathname bytes")
@pytest.mark.parametrize("staged", [False, True])
def test_architecture_check_accepts_non_utf8_path(git_repo, staged):
base = prepare(git_repo)
path = os.fsdecode(b"caf\xe9.txt")
(git_repo / path).write_text("unrelated file\n")
if staged:
git(git_repo, "add", "--", path)

done = run(git_repo, base)
assert done.returncode == 0, done.stderr

(git_repo / "core/CONTRACT.md").write_text("# New authority\n")
done = run(git_repo, base)
assert done.returncode == 1
assert "without guide update or reasoned Architecture-Review trailer" in done.stderr


@pytest.mark.parametrize("sync", ["missing", "guide", "trailer", "empty", "squash"])
def test_architecture_change_requires_update_or_reasoned_review(git_repo, sync):
base = prepare(git_repo)
@pytest.mark.parametrize("sync", ["missing", "guide", "trailer", "empty", "squash",
"untracked-non-utf8", "staged-non-utf8"])
def test_architecture_change_requires_update_or_reasoned_review(git_repo, base, sync):
if sync.endswith("non-utf8"):
if sys.platform != "linux":
pytest.skip("requires raw pathname bytes")
path = os.fsdecode(b"caf\xe9.txt")
(git_repo / path).write_text("unrelated file\n")
if sync == "staged-non-utf8":
git(git_repo, "add", "--", path)
done = run(git_repo, base)
assert done.returncode == 0, done.stderr
git(git_repo, "checkout", "-b", "authored")
(git_repo / "core/CONTRACT.md").write_text("# New authority\n")
if sync == "guide":
Expand All @@ -73,16 +65,14 @@ def test_architecture_change_requires_update_or_reasoned_review(git_repo, sync):


@pytest.mark.parametrize("target", ["absent.md", "../README.md#absent"])
def test_broken_local_link_fails_even_with_guide_update(git_repo, target):
base = prepare(git_repo)
def test_broken_local_link_fails_even_with_guide_update(git_repo, base, target):
(git_repo / "docs/ARCHITECTURE.md").write_text(f"# Current\n[reference]({target})\n")
done = run(git_repo, base)
assert done.returncode == 1
assert "invalid local" in done.stderr


def test_private_code_fix_needs_no_pointless_documentation_edit(git_repo):
base = prepare(git_repo)
def test_private_code_fix_needs_no_pointless_documentation_edit(git_repo, base):
path = git_repo / "src/loopzero/_cli_args.py"
path.parent.mkdir(parents=True)
path.write_text("def build_parser():\n return 'public'\n\ndef _fix():\n return 1\n")
Expand All @@ -96,8 +86,7 @@ def test_private_code_fix_needs_no_pointless_documentation_edit(git_repo):
assert run(git_repo, base).returncode == 1


def test_missing_base_fails_closed(git_repo):
prepare(git_repo)
def test_missing_base_fails_closed(git_repo, base):
assert run(git_repo, "not-a-revision").returncode == 1


Expand Down Expand Up @@ -127,10 +116,6 @@ def test_tach_enforces_module_boundaries(tmp_path):
repo_root = Path(__file__).resolve().parents[1]
tach = Path(sys.executable).with_name("tach")
assert tach.exists(), f"tach not installed next to {sys.executable}"
clean = subprocess.run([str(tach), "check"], cwd=repo_root,
text=True, capture_output=True, check=False)
assert clean.returncode == 0, clean.stdout + clean.stderr

shutil.copy2(repo_root / "tach.toml", tmp_path / "tach.toml")
shutil.copytree(repo_root / "src", tmp_path / "src")
types_py = tmp_path / "src/loopzero/types.py"
Expand Down
220 changes: 98 additions & 122 deletions tests/test_config.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,15 @@
from __future__ import annotations

import json

import pytest

from loopzero import config
from loopzero.types import Config, ResourceLimits, ReviewConfig

FULL = """
[repo]
name = "owner/name"
base = "develop"

[checks]
commands = ["uv run pytest -q", "uv run ruff check ."]
required_ci = ["checks"]
network = true
env_allowlist = ["PATH", "HOME"]
ro_paths = ["/nonexistent/cache", "/tmp/whatever/../cache"]
writable = ["/home/me/.cache/uv"]
scratch = [".venv"]
env = { UV_CACHE_DIR = "/home/me/.cache/uv", UV_PYTHON_DOWNLOADS = "never" }
limits = { memory_mb = 1024, file_mb = 512 }

[checks.inputs]
"uv run pytest -q" = ["src/**"]
"*" = ["lock"]

[delivery]
merge = "rebase"
reviewers = ["codex"]
reviewer_ro_paths = ["/opt/claude", "/opt/codex"]
review_chunk_bytes = 12345

[delivery.review.codex]
model = "gpt-5.6-luna"
effort = "medium"
allowed_efforts = ["low", "medium", "high"]
"""
MINIMAL = '[repo]\nname = "o/n"\n'
COMMANDS = ("uv run pytest -q", "uv run ruff check .")
CHECK_INPUTS = {COMMANDS[0]: ("src/**",), "*": ("lock",)}


def write(tmp_path, text):
Expand All @@ -44,113 +18,109 @@ def write(tmp_path, text):
return path


def table(section, **settings):
# JSON strings, arrays, bools and integers are also valid TOML values.
rows = [f"{json.dumps(key)} = {json.dumps(value)}" for key, value in settings.items()]
return "\n".join([f"[{section}]", *rows, ""])


@pytest.mark.parametrize("strategy,queue", [("rebase", None), ("mergify", "main")])
def test_load_full_config(tmp_path, strategy, queue):
workflow = FULL if queue is None else FULL.replace('merge = "rebase"', 'merge = "mergify"\nmergify_queue = "main"')
review = ReviewConfig("gpt-5.6-luna", "medium", ("low", "medium", "high"))
env = {"UV_CACHE_DIR": "/home/me/.cache/uv", "UV_PYTHON_DOWNLOADS": "never"}
execution = dict(required_ci=("checks",), network=True, env_allowlist=("PATH", "HOME"),
writable=("/home/me/.cache/uv",), scratch=(".venv",))
delivery = dict(reviewers=("codex",), reviewer_ro_paths=("/opt/claude", "/opt/codex"),
review_chunk_bytes=12345)
limits = dict(memory_mb=1024, file_mb=512)
workflow = "".join((
table("repo", name="owner/name", base="develop"),
table("checks", commands=COMMANDS, ro_paths=["/nonexistent/cache", "/tmp/whatever/../cache"], **execution),
table("checks.env", **env), table("checks.limits", **limits),
table("checks.inputs", **CHECK_INPUTS),
table("delivery", merge=strategy, **({"mergify_queue": queue} if queue else {}), **delivery),
table("delivery.review.codex", model=review.model, effort=review.effort, allowed_efforts=review.allowed_efforts),
))
assert config.load(write(tmp_path, workflow)) == Config(
repo="owner/name",
base_branch="develop",
checks=("uv run pytest -q", "uv run ruff check ."),
required_ci=("checks",),
merge_strategy=strategy,
mergify_queue=queue,
reviewers=("codex",),
review={"codex": ReviewConfig("gpt-5.6-luna", "medium", ("low", "medium", "high"))},
reviewer_ro_paths=("/opt/claude", "/opt/codex"),
review_chunk_bytes=12345,
network=True,
env_allowlist=("PATH", "HOME"),
sandbox_ro=("/nonexistent/cache", "/tmp/whatever/../cache"),
writable=("/home/me/.cache/uv",),
scratch=(".venv",),
env=(("UV_CACHE_DIR", "/home/me/.cache/uv"), ("UV_PYTHON_DOWNLOADS", "never")),
limits=ResourceLimits(memory_mb=1024, file_mb=512),
inputs={"uv run pytest -q": ("src/**",), "*": ("lock",)},
repo="owner/name", base_branch="develop", checks=COMMANDS, merge_strategy=strategy, mergify_queue=queue,
review={"codex": review}, sandbox_ro=("/nonexistent/cache", "/tmp/whatever/../cache"), env=tuple(env.items()),
limits=ResourceLimits(**limits), inputs=CHECK_INPUTS, **execution, **delivery,
)

padded = FULL.replace('"uv run pytest -q"', '" uv run pytest -q "')
padded = workflow.replace('"uv run pytest -q"', '" uv run pytest -q "')
assert config.load(write(tmp_path, padded)).checks[0] == " uv run pytest -q "


def test_load_applies_defaults(tmp_path):
loaded = config.load(write(tmp_path, '[repo]\nname = "o/n"\n'))
assert loaded == Config(
repo="o/n",
base_branch="main",
checks=(),
required_ci=(),
merge_strategy="squash",
reviewers=("claude", "codex"),
assert config.load(write(tmp_path, MINIMAL)) == Config(
repo="o/n", base_branch="main", checks=(), required_ci=(), merge_strategy="squash",
reviewers=("claude", "codex"), network=False, env_allowlist=("PATH", "HOME", "LANG", "LC_ALL", "TERM"),
sandbox_ro=(), writable=(), reviewer_ro_paths=(),
scratch=(".venv", ".ruff_cache", ".pytest_cache", "node_modules/.cache"),
limits=ResourceLimits(memory_mb=4096, file_mb=2048),
)
assert loaded.network is False
assert loaded.env_allowlist == ("PATH", "HOME", "LANG", "LC_ALL", "TERM")
assert loaded.sandbox_ro == () and loaded.writable == ()
assert loaded.reviewer_ro_paths == ()
assert loaded.scratch == (".venv", ".ruff_cache", ".pytest_cache", "node_modules/.cache")
assert loaded.limits == ResourceLimits(memory_mb=4096, file_mb=2048)


def test_missing_file(tmp_path):
with pytest.raises(config.ConfigError, match="config file not found"):
config.load(tmp_path / "nope.toml")


@pytest.mark.parametrize(
("text", "message"),
[
("[repo\n", "invalid TOML"),
("[checks]\ncommands = []\n", "missing required key repo.name"),
('[repo]\nname = "noslash"\n', 'must look like "owner/name"'),
('[repo]\nname = 3\n', "repo.name must be a str"),
('[repo]\nname = "o/n"\n[checks]\ncommands = "pytest"\n', "checks.commands must be a list"),
('[repo]\nname = "o/n"\n[checks]\ncommands = ["ok", 1]\n', "non-empty strings"),
('[repo]\nname = "o/n"\n[checks]\ncommands = ["true", " "]\n',
r"workflow\.toml: checks\.commands.*nonblank command"),
('[repo]\nname = "o/n"\n[checks]\nnetwork = "yes"\n', "checks.network must be a bool"),
('[repo]\nname = "o/n"\n[delivery]\nmerge = "ff"\n', "delivery.merge must be one of"),
('[repo]\nname = "o/n"\n[delivery]\nmerge = "mergify"\n', "mergify_queue is required"),
*((f'[repo]\nname = "o/n"\n[delivery]\n{strategy}mergify_queue = "main"\n',
rf"delivery\.mergify_queue.*delivery\.merge.*{selected}")
for strategy, selected in [("", "squash"), ('merge = "squash"\n', "squash"), ('merge = "queue"\n', "queue")]),
(FULL.replace('["src/**"]', '"src"'), r"checks\.inputs"),
('[repo]\nname = "o/n"\n[delivery]\nreviewers = ["gpt"]\n', "delivery.reviewers entries"),
('[repo]\nname = "o/n"\n[repo2]\nx = 1\n', "unknown key\\(s\\) in top level: repo2"),
('[repo]\nname = "o/n"\nnmae = "x"\n', "unknown key\\(s\\) in \\[repo\\]: nmae"),
('repo = "o/n"\n', "\\[repo\\] must be a table"),
('[repo]\nname = "o/n"\nbase = ""\n', "repo.base must not be empty"),
('[repo]\nname = "o/n"\n[delivery]\nreviewers = []\n', "at least one reviewer"),
('[repo]\nname = "o/n"\n[delivery]\nreviewer_ro_paths = ["relative"]\n', "must be absolute"),
*[(f'[repo]\nname = "o/n"\n[delivery]\nreview_chunk_bytes = {value}\n', "int >= 4096")
for value in (0, 1, 4095)],
('[repo]\nname = "o/n"\n[delivery.review.codex]\nmode = "x"\n',
"unknown key\\(s\\) in \\[delivery.review.codex\\]: mode"),
('[repo]\nname = "o/n"\n[delivery.review.codex]\nallowed_efforts = [1]\n',
"allowed_efforts must be a list of non-empty strings"),
('[repo]\nname = "o/n"\n[delivery.review.codex]\nallowed_efforts = "medium"\n',
"allowed_efforts must be a list"),
('[repo]\nname = "o/n"\n[checks]\nro_paths = ["rel/path"]\n', "must be absolute"),
('[repo]\nname = "o/n"\n[checks]\nwritable = ["/run/x"]\n', "writable must not expose"),
('[repo]\nname = "o/n"\n[checks]\nscratch = ["../x"]\n', "scratch entries must be relative"),
('[repo]\nname = "o/n"\n[checks]\nscratch = ["/abs"]\n', "scratch entries must be relative"),
('[repo]\nname = "o/n"\n[checks.env]\nlower = "x"\n', "invalid variable name 'lower'"),
('[repo]\nname = "o/n"\n[checks.env]\nPATH = "/x"\n', "must not override PATH"),
('[repo]\nname = "o/n"\n[checks.env]\nHOME = "/x"\n', "must not override HOME"),
('[repo]\nname = "o/n"\n[checks.env]\nX = 1\n', "checks.env.X must be a str"),
('[repo]\nname = "o/n"\n[checks]\nenv = ["X=1"]\n', "checks.env must be a dict"),
('[repo]\nname = "o/n"\n[checks]\nlimits = 1\n', "checks.limits must be a dict"),
('[repo]\nname = "o/n"\n[checks]\nlimits = { memory_mb = 0 }\n',
"checks.limits.memory_mb must be a positive int"),
('[repo]\nname = "o/n"\n[checks]\nlimits = { cpu = 1 }\n',
"unknown key\\(s\\) in checks.limits: cpu"),
('[repo]\nname = "o/n"\n[checks]\ncommands = ["echo ok"]\n'
'[checks.inputs]\n"echo okay" = ["."]\n', r'checks\.inputs\."echo okay".*exact'),
*[
('[repo]\nname = "o/n"\n[checks]\nrunner = ["runner"]\ncommands = ["true"]\n'
f"[checks.limits]\n{limit} = 1\n", rf"checks\.limits\.{limit}.*local")
for limit in ("file_mb", "memory_mb")
],
],
)
MINIMAL = '[repo]\nname = "o/n"\n'


@pytest.mark.parametrize("text,message", [
("[repo\n", "invalid TOML"),
("[checks]\ncommands = []\n", "missing required key repo.name"),
('[repo]\nname = "noslash"\n', 'must look like "owner/name"'),
('[repo]\nname = 3\n', "repo.name must be a str"),
(MINIMAL + '[checks]\ncommands = "pytest"\n', "checks.commands must be a list"),
*((MINIMAL + f"[checks]\nrunner = {value}", "checks.runner") for value in
('[]', '[""]', '[1]', '"runner"', '["./runner"]', '["tools/runner"]')),
(MINIMAL + '[checks]\ncommands = ["ok", 1]\n', "non-empty strings"),
(MINIMAL + '[checks]\ncommands = ["true", " "]\n',
r"workflow\.toml: checks\.commands.*nonblank command"),
(MINIMAL + '[checks]\nnetwork = "yes"\n', "checks.network must be a bool"),
(MINIMAL + '[delivery]\nmerge = "ff"\n', "delivery.merge must be one of"),
(MINIMAL + '[delivery]\nmerge = "mergify"\n', "mergify_queue is required"),
*((MINIMAL + f'[delivery]\n{strategy}mergify_queue = "main"\n',
rf"delivery\.mergify_queue.*delivery\.merge.*{selected}")
for strategy, selected in [("", "squash"), ('merge = "squash"\n', "squash"), ('merge = "queue"\n', "queue")]),
(MINIMAL + '[checks]\ncommands = ["uv run pytest -q"]\n[checks.inputs]\n"uv run pytest -q" = "src"\n', r"checks\.inputs"),
(MINIMAL + '[delivery]\nreviewers = ["gpt"]\n', "delivery.reviewers entries"),
(MINIMAL + '[repo2]\nx = 1\n', "unknown key\\(s\\) in top level: repo2"),
(MINIMAL + 'nmae = "x"\n', "unknown key\\(s\\) in \\[repo\\]: nmae"),
('repo = "o/n"\n', "\\[repo\\] must be a table"),
(MINIMAL + 'base = ""\n', "repo.base must not be empty"),
(MINIMAL + '[delivery]\nreviewers = []\n', "at least one reviewer"),
(MINIMAL + '[delivery]\nreviewer_ro_paths = ["relative"]\n', "must be absolute"),
*[(MINIMAL + f'[delivery]\nreview_chunk_bytes = {value}\n', "int >= 4096")
for value in (0, 1, 4095)],
(MINIMAL + '[delivery.review.codex]\nmode = "x"\n',
"unknown key\\(s\\) in \\[delivery.review.codex\\]: mode"),
(MINIMAL + '[delivery.review.codex]\nallowed_efforts = [1]\n',
"allowed_efforts must be a list of non-empty strings"),
(MINIMAL + '[delivery.review.codex]\nallowed_efforts = "medium"\n',
"allowed_efforts must be a list"),
(MINIMAL + '[checks]\nro_paths = ["rel/path"]\n', "must be absolute"),
(MINIMAL + '[checks]\nwritable = ["/run/x"]\n', "writable must not expose"),
*((MINIMAL + f'[checks]\nscratch = ["{path}"]\n', "scratch entries must be relative")
for path in ("../x", "/abs")),
(MINIMAL + '[checks.env]\nlower = "x"\n', "invalid variable name 'lower'"),
*((MINIMAL + f'[checks.env]\n{key} = "/x"\n', f"must not override {key}")
for key in ("PATH", "HOME")),
(MINIMAL + '[checks.env]\nX = 1\n', "checks.env.X must be a str"),
(MINIMAL + '[checks]\nenv = ["X=1"]\n', "checks.env must be a dict"),
(MINIMAL + '[checks]\nlimits = 1\n', "checks.limits must be a dict"),
(MINIMAL + '[checks]\nlimits = { memory_mb = 0 }\n',
"checks.limits.memory_mb must be a positive int"),
(MINIMAL + '[checks]\nlimits = { cpu = 1 }\n',
"unknown key\\(s\\) in checks.limits: cpu"),
(MINIMAL + '[checks]\ncommands = ["echo ok"]\n'
'[checks.inputs]\n"echo okay" = ["."]\n', r'checks\.inputs\."echo okay".*exact'),
*((MINIMAL + '[checks]\nrunner = ["runner"]\ncommands = ["true"]\n'
f"[checks.limits]\n{limit} = 1\n", rf"checks\.limits\.{limit}.*local")
for limit in ("file_mb", "memory_mb")),
])
def test_invalid_content(tmp_path, text, message):
with pytest.raises(config.ConfigError, match=message) as info:
config.load(write(tmp_path, text))
Expand All @@ -161,6 +131,12 @@ def test_invalid_content(tmp_path, text, message):
FORBIDDEN += ["/var/run/docker.sock", "/sys/fs", "/tmp/../run"]


@pytest.mark.parametrize("runner", [("dispatch", "--stage"), ("python3", "tools/run_stage.py"),
("dispatch", "--opt=/operator/run.py")])
def test_runner_prefix(tmp_path, runner):
assert config.load(write(tmp_path, MINIMAL + f"[checks]\nrunner = {list(runner)!r}")).check_runner == runner


@pytest.mark.parametrize("path,allowed", [
*((path, False) for path in FORBIDDEN),
*((path, True) for path in ("/home/me/.local/bin", "/opt/tool", "/tmp/x")),
Expand Down
Loading
Loading