Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
fda1970
Keep PR content from hiding changed code from the reviewer
eowca Nov 25, 2026
a2830cd
Classify reviewer files by content and parse Git output as bytes
eowca Nov 26, 2026
3054d0b
Classify reviewer files by full object ID with bounded reads
eowca Nov 26, 2026
f8f235a
Merge remote-tracking branch 'origin/main' into lean178/1101-reviewer…
eowca Nov 26, 2026
775c423
Merge remote-tracking branch 'origin/main' into lean178/1101-reviewer…
eowca Nov 26, 2026
03267ea
Compact reviewer diff integrity tests
eowca Nov 26, 2026
70e478b
Diff submodule pointers and fail closed on lost blob reads
eowca Nov 26, 2026
48e31d5
Merge remote-tracking branch 'origin/main' into lean178/1101-reviewer…
eowca Nov 26, 2026
32b534a
Share repeated fixtures and assertions across delivery tests
eowca Nov 26, 2026
44fa248
Bound Mergify candidate conditions in timeout output
eowca Nov 26, 2026
b0b358b
Accept the reviewer patch options in native inspection evidence
eowca Nov 26, 2026
7047e06
Merge main and keep its landed metrics test dedupe
eowca Nov 26, 2026
b36d5a7
Keep the existing Mergify fixture setup mergeable
eowca Nov 26, 2026
5073306
Merge remote-tracking branch 'origin/main' into lean178/1458-bound-me…
eowca Nov 26, 2026
ac76ad7
Keep the reviewer diff tests out of the shared import block
eowca Nov 26, 2026
7725381
Merge main and keep its updated alternate probe tests
eowca Nov 26, 2026
00aca9e
Merge of PR 1564
mergify[bot] Nov 26, 2026
8bf95a7
Merge of PR 1486
mergify[bot] Nov 26, 2026
e301130
Merge of PR 1511
mergify[bot] Nov 26, 2026
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
5 changes: 4 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,10 @@ commit identity stays in the JSON material header. Explicit UTF-8 stdin carries
that header, a newline and the Git patch, including carriage returns and the
final newline. UTF-8 patches are supplied verbatim. For other patches, the
prompt escapes invalid bytes and literal backslashes so the changes stay
visible. The native inspection digest always binds the original Git bytes.
visible. The native inspection digest always binds the original Git bytes. Git forces
text hunks for every file (overriding `-diff`, `binary` and NUL detection) and
runs no external diff command or text conversion, so changed lines stay visible.
Chunked review summarizes only files whose Git header reports a deletion.
The runner probes the selected Codex binary with `--version` and records its
stdout in runner provenance and the saved review receipt. A failed probe uses
RunnerBadOutput and existing family fallback before model input. Successful
Expand Down
7 changes: 6 additions & 1 deletion src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1463,7 +1463,12 @@ def _mergify_timeout_detail(
)
detail = f"still queued in {queue}. {location}"
if state.unmet_conditions:
detail += ". Unmet candidate conditions: " + "; ".join(state.unmet_conditions)
labels = [label.encode() for label in state.unmet_conditions[:4]]
shown = [label[:160].decode(errors="ignore") + ("…" if len(label) > 160 else "")
for label in labels]
detail += ". Unmet candidate conditions: " + "; ".join(shown)
if omitted := len(state.unmet_conditions) - len(shown):
detail += f"; {omitted} more"
return detail


Expand Down
6 changes: 4 additions & 2 deletions src/loopzero/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -813,7 +813,8 @@ def _inspection_commands(command, cwd):
args = [
part
for part in group[1:]
if part not in {"--no-color", "--no-ext-diff", "--no-textconv"}
if part not in {"--no-color", "--no-ext-diff", "--no-textconv", "--text",
"--ignore-submodules=none", "--submodule=short"}
]
if len(args) != 2 or not all(_hex(part, 40) for part in args):
return []
Expand Down Expand Up @@ -1384,7 +1385,8 @@ def split_diff(diff: str, budget: int) -> list[str]:


def _summarize_deleted(block: str) -> str:
if "\ndeleted file mode " not in block and "\n+++ /dev/null" not in block:
# Judge deletion from git's header lines only; hunk lines are the PR's own text.
if not re.search(r"(?m)^deleted file mode [0-7]{6}$", block.partition("\n@@")[0]):
return block
header = block.partition("\n")[0]
match = re.fullmatch(r'diff --git ("?)a/(.*)\1 \1b/\2\1', header)
Expand Down
5 changes: 4 additions & 1 deletion src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,10 @@ def is_dirty(wt: Path) -> bool:


def diff_since(wt: Path, sha: str) -> bytes:
diff = _git(Path(wt), "diff", "--no-color", sha, "HEAD", preserve_newlines=True)
# Show every file as text, whatever attributes or NUL bytes the reviewed head adds,
# without diff drivers, and keep submodule pointers even if .gitmodules ignores them.
diff = _git(Path(wt), "diff", "--no-color", "--no-ext-diff", "--no-textconv", "--text",
"--ignore-submodules=none", "--submodule=short", sha, "HEAD", preserve_newlines=True)
return diff.encode("utf-8", errors="surrogateescape")


Expand Down
48 changes: 18 additions & 30 deletions tests/test_candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,21 +105,24 @@ def payloads(candidate_event: dict) -> dict[str, object]:


def run_attestation(
*,
candidate_event: dict | None = None,
*,
status_reads: list[dict] | None = None,
github_payloads: dict[str, object] | None = None,
github_get=None,
mergify_status=None,
source_policy=lambda _number, _source: None,
run=attest_candidate,
):
candidate_event = candidate_event or event()
reads, values = (
cycle(status_reads or [status(), status()]),
github_payloads or payloads(candidate_event),
)
return attest_candidate(
return run(
candidate_event,
github_get=lambda path: deepcopy(values[path]),
mergify_status=lambda *_: deepcopy(next(reads)),
github_get=github_get or (lambda path: deepcopy(values[path])),
mergify_status=mergify_status or (lambda *_: deepcopy(next(reads))),
source_policy=source_policy,
)

Expand Down Expand Up @@ -187,10 +190,8 @@ def github_get(path: str):

reads = iter([status(), status()])
with pytest.raises(CandidateError, match=diagnostic):
attest_candidate(
candidate_event, github_get=github_get,
mergify_status=lambda *_: deepcopy(next(reads)), source_policy=lambda *_: None,
)
run_attestation(candidate_event, github_get=github_get,
mergify_status=lambda *_: deepcopy(next(reads)))


def test_same_head_still_obeys_source_policy() -> None:
Expand Down Expand Up @@ -286,8 +287,8 @@ def get(path):
return deepcopy(values[path])
return {"object": {"sha": sha}} if (sha := next(reads)) else {}

return run(candidate_event, github_get=get, mergify_status=lambda *_: deepcopy(queue),
source_policy=policy)
return run_attestation(candidate_event, github_get=get, status_reads=[queue],
source_policy=policy, run=run)

return attest, git, commit, base, parent, source, candidate_sha

Expand Down Expand Up @@ -520,7 +521,8 @@ def verify_tree(repo, main_sha, candidate_sha, sources):

monkeypatch.setattr(candidate, "_retry_sleep", sleeps.append)
monkeypatch.setattr(candidate, "_verify_tree", verify_tree)
assert attest_candidate(candidate_event, github_get=get, mergify_status=lineage, source_policy=policy) == [{"number": 102, "head_sha": source}]
assert run_attestation(candidate_event, github_get=get, mergify_status=lineage,
source_policy=policy) == [{"number": 102, "head_sha": source}]
assert seen == {"metadata": [101, 102, 102], "policy": [101, 102], "initial": [102]}[timing]
assert candidate_reads == (4 if timing == "metadata" else 3)
assert verified == [(main, head, [source])] and sleeps == [2]
Expand All @@ -545,12 +547,7 @@ def policy(number, source):
raise CandidateError("fresh policy rejects drift")

with pytest.raises(CandidateError, match="fresh policy rejects drift"):
attest_candidate(
event(),
github_get=get,
mergify_status=lambda *_: status(),
source_policy=policy,
)
run_attestation(github_get=get, source_policy=policy)
assert snapshots == [
("source 101", False),
(value if field == "body" else "source 101", field == "draft"),
Expand Down Expand Up @@ -598,12 +595,7 @@ def policy(*_):

monkeypatch.setattr(candidate, "_retry_sleep", sleeps.append)
with pytest.raises((CandidateError, LoopZeroError)) as caught:
attest_candidate(
event(),
github_get=get,
mergify_status=lambda *_: deepcopy(live),
source_policy=policy,
)
run_attestation(github_get=get, status_reads=[live], source_policy=policy)
assert not isinstance(caught.value, CandidateRaceError) and len(attempts) == 1 and sleeps == []
if failure == "policy":
assert caught.value is expected and len(source_reads) == 2
Expand Down Expand Up @@ -632,12 +624,7 @@ def sleep(seconds):
monkeypatch.setattr(candidate, "_retry_clock", lambda: clock[0])
monkeypatch.setattr(candidate, "_retry_sleep", sleep)
with pytest.raises(CandidateRaceError, match="membership changed") as caught:
attest_candidate(
event(),
github_get=lambda _: None,
mergify_status=lambda *_: None,
source_policy=lambda *_: None,
)
run_attestation(github_get=lambda _: None, status_reads=[None])
assert len(attempts) == attempt_count and caught.value is attempts[-1]
assert sum(sleeps) <= 4

Expand Down Expand Up @@ -673,7 +660,8 @@ def read_status(*_):
monkeypatch.setattr(candidate, "_retry_clock", lambda: clock[0])
monkeypatch.setattr(candidate, "_retry_sleep", sleep)
def run():
return attest_candidate(event(), github_get=lambda p: deepcopy(values[p]), mergify_status=read_status, source_policy=lambda n, _: seen.append(n))
return run_attestation(github_payloads=values, mergify_status=read_status,
source_policy=lambda n, _: seen.append(n))
if stop in {"settled", "changed"}:
assert run() == [{"number": 101, "head_sha": "1" * 40}, {"number": 102, "head_sha": "2" * 40}]
assert seen == [101, 102] * (2 if stop == "changed" and second else 1)
Expand Down
20 changes: 10 additions & 10 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4452,22 +4452,22 @@ def test_mergify_reports_current_queue_attempt(wt, gh, capsys, monkeypatch, conf
assert (f"{URL}#issuecomment-43" in out) is (kind == "current")


@pytest.mark.parametrize("result", ["blocking", "neutral", "skipped", None])
@pytest.mark.parametrize("result", ["blocking", "neutral", "skipped", None, "long", "many"])
def test_mergify_timeout_reports_evaluated_candidate_conditions(wt, gh, capsys, monkeypatch, result):
head = commit_mergify_configuration(wt)
arm_approved_ready_pr(gh, head, wt, isDraft=False)
monkeypatch.setattr(mergify, "configured", lambda *_: True)
monkeypatch.setattr(mergify, "markers", lambda *_: (True, False))
monkeypatch.setattr(mergify, "mark_confirmed", lambda *_: None)
responses = iter([None, MERGIFY_QUEUE_FIXTURE["candidate_responses"][result or "missing"]])
monkeypatch.setattr(mergify, "api_get", lambda *_: next(responses))

monkeypatch.setattr(mergify, "markers", lambda *_: (True, True))
payload = MERGIFY_QUEUE_FIXTURE["candidate_responses"]["blocking" if result in {"long", "many"} else result or "missing"]
if extra := {"long": 1, "many": 30}.get(result, 0):
conditions = payload["mergeability_check"]["conditions_evaluation"]
monkeypatch.setitem(conditions, "subconditions", conditions["subconditions"] + [{"match": False, "label": "界" * 3000}] * extra)
monkeypatch.setattr(mergify, "api_get", lambda *_: payload)
code, out, err = run(capsys, "merge", "--wait=0")

assert (code, err) == (3, "")
assert f"https://github.com/{REPO}/pull/42" in out
assert (MERGIFY_QUEUE_FIXTURE["candidate_condition"] in out) is (result == "blocking")
assert (code, err) == (3, "") and f"https://github.com/{REPO}/pull/42" in out
assert (MERGIFY_QUEUE_FIXTURE["candidate_condition"] in out) == (result in {"blocking", "long", "many"})
assert "failed" not in out and "check-success = checks" not in out
assert len(out.encode()) < 2048 and ("27 more" in out) == (extra == 30)


@pytest.mark.parametrize("queue_state", ["unsafe", "error", "safe", "becomes_unsafe"])
Expand Down
50 changes: 19 additions & 31 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,14 +102,10 @@ def test_missing_file(tmp_path):
config.load(tmp_path / "nope.toml")


def test_invalid_toml(tmp_path):
with pytest.raises(config.ConfigError, match="invalid TOML"):
config.load(write(tmp_path, "[repo\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"),
Expand Down Expand Up @@ -148,6 +144,13 @@ def test_invalid_toml(tmp_path):
"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")
],
],
)
def test_invalid_content(tmp_path, text, message):
Expand All @@ -160,17 +163,17 @@ def test_invalid_content(tmp_path, text, message):
FORBIDDEN += ["/var/run/docker.sock", "/sys/fs", "/tmp/../run"]


@pytest.mark.parametrize("path", FORBIDDEN)
def test_ro_paths_reject_host_secrets(tmp_path, path):
text = f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n'
with pytest.raises(config.ConfigError, match="must not expose"):
config.load(write(tmp_path, text))


@pytest.mark.parametrize("path", ["/home/me/.local/bin", "/opt/tool", "/tmp/x"])
def test_ro_paths_accept_explicit_subpaths(tmp_path, path):
text = f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n'
assert config.load(write(tmp_path, text)).sandbox_ro == (path,)
@pytest.mark.parametrize("path,allowed", [
*((path, False) for path in FORBIDDEN),
*((path, True) for path in ("/home/me/.local/bin", "/opt/tool", "/tmp/x")),
])
def test_ro_path_boundary(tmp_path, path, allowed):
cfg = write(tmp_path, f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n')
if allowed:
assert config.load(cfg).sandbox_ro == (path,)
else:
with pytest.raises(config.ConfigError, match="must not expose"):
config.load(cfg)


def test_check_inputs(tmp_path):
Expand All @@ -180,24 +183,9 @@ def test_check_inputs(tmp_path):
config.load(write(tmp_path, FULL + '\n[checks.inputs]\n"uv run pytest -q" = "src"\n'))


def test_check_inputs_reject_unmatched_command(tmp_path):
text = '[repo]\nname = "o/n"\n[checks]\ncommands = ["echo ok"]\n'
text += '[checks.inputs]\n"echo okay" = ["."]\n'
with pytest.raises(config.ConfigError, match=r'checks\.inputs\."echo okay".*exact'):
config.load(write(tmp_path, text))


@pytest.mark.parametrize("strategy", ["", 'merge = "squash"\n', 'merge = "queue"\n'])
def test_mergify_queue_rejects_other_strategies(tmp_path, strategy):
selected = "queue" if "queue" in strategy else "squash"
text = '[repo]\nname = "o/n"\n[delivery]\n' + strategy + 'mergify_queue = "main"\n'
with pytest.raises(config.ConfigError, match=rf"delivery\.mergify_queue.*delivery\.merge.*{selected}"):
config.load(write(tmp_path, text))


@pytest.mark.parametrize("limit", ["file_mb", "memory_mb"])
def test_delegated_runner_rejects_local_limit_overrides(tmp_path, limit):
text = '[repo]\nname = "o/n"\n[checks]\nrunner = ["runner"]\ncommands = ["true"]\n'
text += f"[checks.limits]\n{limit} = 1\n"
with pytest.raises(config.ConfigError, match=rf"checks\.limits\.{limit}.*local"):
config.load(write(tmp_path, text))
64 changes: 21 additions & 43 deletions tests/test_mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,8 @@
from loopzero import mergify


class Response(io.BytesIO):
def __enter__(self):
return self

def __exit__(self, *_args):
self.close()


def response(payload: object) -> Response:
return Response(json.dumps(payload).encode())
def response(payload: object) -> io.BytesIO:
return io.BytesIO(json.dumps(payload).encode())


def test_membership_uses_bearer_and_validates_queue(monkeypatch):
Expand Down Expand Up @@ -86,7 +78,7 @@ def queue_api(monkeypatch):
{"batches": [], "mode": "serial"} if suffix.startswith("/merge-queue/status") else
{"configuration": [{"name": "main", "config": {"allow_inplace_checks": True}}]}
))
def github_config(text, *, default="main", changed=False):
def github_config(text, *, default="main", changed=False, file_overrides=None):
reads = 0
def get(path):
nonlocal reads
Expand All @@ -95,7 +87,7 @@ def get(path):
assert path == "repos/acme/widgets/contents/.mergify.yml?ref=refs%2Fheads%2Fmain"
reads += 1
return {"type": "file", "encoding": "base64", "sha": str(reads if changed else 1)*40,
"content": base64.b64encode(text.encode()).decode()}
"content": base64.b64encode(text.encode()).decode(), **(file_overrides or {})}
monkeypatch.setattr(mergify.github, "api_get", get)
return github_config

Expand All @@ -104,13 +96,7 @@ def get(path):
ONE_CHECK = SAFE_CONFIG.replace("checks: 3", "checks: 1") # in place unless batches are explicit


@pytest.mark.parametrize("text", [SAFE_CONFIG, ONE_CHECK.replace("main}", "main, batch_size: 8}")])
def test_configured_accepts_documented_speculation_despite_raw_inplace_default(queue_api, text):
queue_api(text)
assert mergify.configured("acme/widgets", "main", "main")


@pytest.mark.parametrize("text", [
UNSAFE_CONFIGS = [
SAFE_CONFIG.replace("checks: 3", f"checks: {value}")
for value in ["1", "0", "-1", "true", '"3"', "null"]
] + [
Expand All @@ -120,16 +106,22 @@ def test_configured_accepts_documented_speculation_despite_raw_inplace_default(q
SAFE_CONFIG + "merge_queue: {max_parallel_checks: 1}\n",
"[]", "!!python/object:object {}", "merge_queue: [",
] + [ONE_CHECK.replace("main}", r) for r in ["main, batch_size: 1}", "main, batch_size: true}",
'main, batch_size: "8"}', "main, batch_size: null}", "main}, {name: o, batch_size: 8}"]])
def test_configured_rejects_unsafe_or_ambiguous_canonical_config(queue_api, text):
queue_api(text)
assert not mergify.configured("acme/widgets", "main", "main")


@pytest.mark.parametrize("options", [{"default": "other"}, {"changed": True}])
def test_configured_rejects_wrong_default_branch_or_config_change(queue_api, options):
queue_api(SAFE_CONFIG, **options)
assert not mergify.configured("acme/widgets", "main", "main")
'main, batch_size: "8"}', "main, batch_size: null}", "main}, {name: o, batch_size: 8}"]]


@pytest.mark.parametrize("text,options,accepted", [
(SAFE_CONFIG, {}, True),
(ONE_CHECK.replace("main}", "main, batch_size: 8}"), {}, True),
*((text, {}, False) for text in UNSAFE_CONFIGS),
(SAFE_CONFIG, {"default": "other"}, False),
(SAFE_CONFIG, {"changed": True}, False),
*((SAFE_CONFIG, {"file_overrides": {key: value}}, False)
for key, value in (("encoding", "none"), ("type", "symlink"), ("sha", None),
("sha", "z" * 40), ("content", None), ("content", "!"))),
])
def test_configured_validates_canonical_github_config(queue_api, text, options, accepted):
queue_api(text, **options)
assert mergify.configured("acme/widgets", "main", "main") == accepted


def test_configured_still_requires_vendor_queue_identity(queue_api, monkeypatch):
Expand All @@ -138,20 +130,6 @@ def test_configured_still_requires_vendor_queue_identity(queue_api, monkeypatch)
assert not mergify.configured("acme/widgets", "main", "main")


@pytest.mark.parametrize("field,value", [("encoding", "none"), ("type", "symlink"),
("sha", None), ("sha", "z"*40), ("content", None), ("content", "!")])
def test_configured_rejects_malformed_github_file(queue_api, monkeypatch, field, value):
queue_api(SAFE_CONFIG)
original = mergify.github.api_get
def malformed(path):
data = original(path)
if "/contents/" in path:
data[field] = value
return data
monkeypatch.setattr(mergify.github, "api_get", malformed)
assert not mergify.configured("acme/widgets", "main", "main")


def test_legacy_false_does_not_license_single_check_source_updates(queue_api, monkeypatch):
queue_api(SAFE_CONFIG.replace("checks: 3", "checks: 1"))
monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix: (
Expand Down
Loading
Loading