From 07832b4449d25e633440b0ca70b45f1ba523f4ac Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:48:49 +0100 Subject: [PATCH 1/3] Follow an existing Mergify entry when admission is blocked Architecture-Review: unchanged; Existing authenticated membership uses the exact-head follower with unchanged admission gates. Co-Authored-By: Codex --- src/loopzero/cli.py | 9 ++++++--- tests/test_cli.py | 17 +++++++++++++++-- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index e9136315..6be0910c 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1710,12 +1710,15 @@ def _merge_with_mergify( wt: Path, config: Config, pr: github.PR, readiness: github.Readiness, deadline: float | None, admit_by: float | None = None, ) -> str | None: - """Request Mergify after readiness verifies the source gates and queue configuration.""" + """Request admission after readiness, or observe a live queue entry without writing.""" + queue = config.mergify_queue + assert queue is not None if not readiness.ready: + if (deadline is not None and pr.base_ref == config.base_branch + and mergify.membership(config.repo, pr.number, queue) is not None): + return _wait_for_mergify(config, pr, max(0.0, deadline - time.monotonic()), True) hint = _merge_check_hint(config, pr, readiness) raise CliError("not ready to request Mergify: " + "; ".join(_readiness_messages(pr, readiness)) + hint) - queue = config.mergify_queue - assert queue is not None requested, confirmed_marker = mergify.markers( config.repo, pr.number, pr.head_sha, queue ) diff --git a/tests/test_cli.py b/tests/test_cli.py index db219611..690ea0ae 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4376,6 +4376,9 @@ def membership(*_): ("head_changed", 1.0), ("timeout", 0.9), ("timeout", 1.0), + ("incompatible_landed", 1.0), + ("incompatible_absent", 1.0), + ("incompatible_unverified", 1.0), ("api_error", 1.0), ("unsafe_config", 1.0), ("config_error", 1.0), @@ -4392,9 +4395,12 @@ def test_mergify_wait_outcomes_preserve_unmerged_work(wt, repo, gh, capsys, monk gh, head, wt, "success", isDraft=False, state="MERGED" if outcome.startswith("already_") else "OPEN", ) + if outcome.startswith("incompatible_"): + receipt = wt / ".loopzero/checks.json" + receipt.write_text(json.dumps({**json.loads(receipt.read_text()), "settings_sha256": "0" * 64})) gh.respond("api -X", "") landed = outcome in { - "merged", "worktree_removed", "merged_head_changed", "already_merged", "already_merged_changed", + "merged", "incompatible_landed", "worktree_removed", "merged_head_changed", "already_merged", "already_merged_changed", } snapshots = [] if not outcome.startswith("already_"): @@ -4425,6 +4431,10 @@ def configured(*_): reads = [] def membership(*_): reads.append(True) + if outcome == "incompatible_absent": + return None + if outcome == "incompatible_unverified": + raise mergify.MergifyError("HTTP 503") if outcome in {"unsafe_pending", "requested_head_changed"} and len(reads) == 1: return None if len(reads) > 1: @@ -4454,7 +4464,9 @@ def remove_worktree_then_poll(*args, **kwargs): assert sum(c["argv"][:2] == PR_LIST_READ for c in gh.calls) == 1 assert sum(c["argv"][:2] == ["api", "graphql"] for c in gh.calls) == 2 assert requests == ([(REPO, 7, head, "main")] if outcome == "requested_head_changed" else []) - if outcome in {"merged", "already_merged", "worktree_removed"}: + if outcome.startswith("incompatible_"): + assert reads == [True] * (2 if landed else 1) + if outcome in {"merged", "incompatible_landed", "already_merged", "worktree_removed"}: assert code == 0 and "e" * 40 in out and not wt.exists(), err if outcome == "worktree_removed": assert "warning: merged but worktree cleanup failed" in err @@ -4465,6 +4477,7 @@ def remove_worktree_then_poll(*args, **kwargs): assert err.index('"Left the queue" comment') < err.index("post `@mergifyio queue`") message = {"ejected": "post `@mergifyio queue` as the whole PR comment (same login), then rerun `loopzero merge --wait`", "head_changed": "head changed", "timeout": "timed out", "api_error": "HTTP 503", + "incompatible_absent": "incompatible settings fingerprint", "incompatible_unverified": "HTTP 503", "unsafe_config": "unsafe or unavailable", "unsafe_pending": "unsafe or unavailable", "config_error": "HTTP 503", "requested_head_changed": "head changed", "merged_head_changed": "head changed", "already_merged_changed": "head changed", "ejection_head_changed": "head changed"}[outcome] assert message in out + err From 256d254b2b7b5932e2dfa2a0dd1eead21651afd9 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:59:36 +0100 Subject: [PATCH 2/3] Preserve readiness guidance when membership cannot be read Co-Authored-By: Codex --- src/loopzero/cli.py | 21 ++++++++++++++++----- tests/test_cli.py | 2 ++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 6be0910c..dd0b2263 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1706,6 +1706,21 @@ class _AdmissionDeadline(Exception): """The --wait budget expired before a new merge or queue request.""" +def _follow_blocked_mergify( + config: Config, pr: github.PR, readiness: github.Readiness, queue: str, deadline: float | None, +) -> str | None: + hint = _merge_check_hint(config, pr, readiness) + try: + confirmed = (deadline is not None and pr.base_ref == config.base_branch + and mergify.membership(config.repo, pr.number, queue) is not None) + except mergify.MergifyError as exc: + confirmed = False + hint += f"; Mergify membership unverified: {exc}" + if confirmed: + return _wait_for_mergify(config, pr, max(0.0, deadline - time.monotonic()), True) + raise CliError("not ready to request Mergify: " + "; ".join(_readiness_messages(pr, readiness)) + hint) + + def _merge_with_mergify( wt: Path, config: Config, pr: github.PR, readiness: github.Readiness, deadline: float | None, admit_by: float | None = None, @@ -1714,11 +1729,7 @@ def _merge_with_mergify( queue = config.mergify_queue assert queue is not None if not readiness.ready: - if (deadline is not None and pr.base_ref == config.base_branch - and mergify.membership(config.repo, pr.number, queue) is not None): - return _wait_for_mergify(config, pr, max(0.0, deadline - time.monotonic()), True) - hint = _merge_check_hint(config, pr, readiness) - raise CliError("not ready to request Mergify: " + "; ".join(_readiness_messages(pr, readiness)) + hint) + return _follow_blocked_mergify(config, pr, readiness, queue, deadline) requested, confirmed_marker = mergify.markers( config.repo, pr.number, pr.head_sha, queue ) diff --git a/tests/test_cli.py b/tests/test_cli.py index 690ea0ae..ee6c0dbe 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4466,6 +4466,8 @@ def remove_worktree_then_poll(*args, **kwargs): assert requests == ([(REPO, 7, head, "main")] if outcome == "requested_head_changed" else []) if outcome.startswith("incompatible_"): assert reads == [True] * (2 if landed else 1) + if not landed: + assert "incompatible settings fingerprint" in err if outcome in {"merged", "incompatible_landed", "already_merged", "worktree_removed"}: assert code == 0 and "e" * 40 in out and not wt.exists(), err if outcome == "worktree_removed": From 2b3e62d52dc2c1c0f21712957a4beba8070a9842 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:00:50 +0100 Subject: [PATCH 3/3] Share workflow decoding and remove redundant validation paths Architecture-Review: unchanged; local and trusted workflow inputs retain their validation rules and errors, and review evidence checks keep the same order. Co-Authored-By: Codex --- src/loopzero/_cli_args.py | 9 ++--- src/loopzero/config.py | 65 ++++++++++++++++--------------------- src/loopzero/eligibility.py | 7 ++-- 3 files changed, 33 insertions(+), 48 deletions(-) diff --git a/src/loopzero/_cli_args.py b/src/loopzero/_cli_args.py index ce9af047..c154e28d 100644 --- a/src/loopzero/_cli_args.py +++ b/src/loopzero/_cli_args.py @@ -5,6 +5,7 @@ import argparse import io import sys +from pathlib import Path WAIT_TIMEOUT = 1800.0 @@ -21,18 +22,12 @@ def _wait_seconds(value: str) -> float: raise argparse.ArgumentTypeError("expected a finite, nonnegative number of seconds") -def _config_path(value: str): - from pathlib import Path - - return Path(value) - - def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="loopzero", description="One task, one branch, one draft PR, one review, one merge." ) parser.add_argument( - "--config", type=_config_path, default=None, help="path to workflow.toml (default: repo root)" + "--config", type=Path, help="path to workflow.toml (default: repo root)" ) parser.add_argument("--version", action=_VersionAction, nargs=0, help="show program's version number and exit") sub = parser.add_subparsers(dest="command", required=True) diff --git a/src/loopzero/config.py b/src/loopzero/config.py index 97db3d8f..6fd5279d 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -18,7 +18,6 @@ # Host locations that must never be exposed to the sandbox, even read-only, because they # hold credentials or live sockets (docker, ssh-agent, gpg-agent, dbus). Subpaths of /home # are allowed so tool caches such as ~/.local/bin can be listed explicitly. -FORBIDDEN_RO = ("/", "/home", "/root", "/run", "/var/run", "/proc", "/dev", "/sys") _ENV_NAME = re.compile(r"[A-Z_][A-Z0-9_]*\Z") FORBIDDEN_RO_TREES = ("/run", "/var/run", "/proc", "/dev", "/sys", "/root") @@ -45,8 +44,7 @@ def load(path: Path | str) -> Config: """Load and validate a workflow file.""" path = Path(path) try: - with path.open("rb") as handle: - data = tomllib.load(handle) + raw = path.read_bytes() except FileNotFoundError as exc: raise ConfigError( f"{path}: config file not found. Check out the intended repository, " @@ -54,14 +52,18 @@ def load(path: Path | str) -> Config: "(https://github.com/feder-positronics/loop-zero/blob/main/SETUP.md#configure), " "or follow this repository's review process if it has one." ) from exc - except UnicodeDecodeError as exc: - raise ConfigError(f"{path}: {exc}") from exc - except tomllib.TOMLDecodeError as exc: - raise ConfigError(f"{path}: invalid TOML: {exc}") from exc + return _parse_workflow(raw, path) + + +def _parse_workflow(raw: bytes, source: Path | str, hint: str = "") -> Config: try: - return _build(data) - except ConfigError as exc: - raise ConfigError(f"{path}: {exc}") from None + return _build(tomllib.loads(raw.decode("utf-8"))) + except UnicodeDecodeError as exc: + raise ConfigError(f"{source}: {exc}") from exc + except (tomllib.TOMLDecodeError, ConfigError) as exc: + invalid_toml = isinstance(exc, tomllib.TOMLDecodeError) + message = f"invalid TOML: {exc}" if invalid_toml else str(exc) + raise ConfigError(f"{source}: {message}{hint}") from (exc if invalid_toml and not hint else None) def run_git(worktree: Path, *args: str, timeout: float = 60) -> _proc.Completed: @@ -124,15 +126,7 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, ) if shown.exit_code != 0: raise ConfigError(f"cannot read {source}. {hint}") - try: - text = shown.stdout.encode("utf-8", errors="surrogateescape").decode("utf-8") - return _build(tomllib.loads(text)), revision - except UnicodeDecodeError as exc: - raise ConfigError(f"{source}: {exc}") from exc - except tomllib.TOMLDecodeError as exc: - raise ConfigError(f"{source}: invalid TOML: {exc}. {hint}") from None - except ConfigError as exc: - raise ConfigError(f"{source}: {exc}. {hint}") from None + return _parse_workflow(shown.stdout.encode("utf-8", "surrogateescape"), source, f". {hint}"), revision def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: bool = False, @@ -147,13 +141,12 @@ def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: boo "or supply --config for bootstrap or an override." ) branch = ref.removeprefix(prefix) - policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh, read_timeout=read_timeout) - if policy.base_branch != branch: - branch = policy.base_branch + for _ in range(2): policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh, read_timeout=read_timeout) - if policy.base_branch != branch: - raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config") - return replace(policy, trusted_base_revision=revision) + if policy.base_branch == branch: + return replace(policy, trusted_base_revision=revision) + branch = policy.base_branch + raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config") def _build(data: dict[str, Any]) -> Config: @@ -269,14 +262,13 @@ def _merge_settings(delivery: dict[str, Any]) -> tuple[str, str | None]: if merge not in MERGE_STRATEGIES: raise ConfigError(f"delivery.merge must be one of {MERGE_STRATEGIES}, got {merge!r}") mergify_queue = delivery.get("mergify_queue") - if merge == "mergify" and not mergify_queue: - raise ConfigError("delivery.mergify_queue is required when delivery.merge = 'mergify'") - if mergify_queue is not None and merge != "mergify": - raise ConfigError( - f"delivery.mergify_queue requires delivery.merge = 'mergify', got {merge!r}" - ) - if mergify_queue is not None and not re.fullmatch(r"[A-Za-z0-9_-]+", mergify_queue): - raise ConfigError("delivery.mergify_queue must be a non-empty command-safe name") + if merge == "mergify": + if not mergify_queue: + raise ConfigError("delivery.mergify_queue is required when delivery.merge = 'mergify'") + if not re.fullmatch(r"[A-Za-z0-9_-]+", mergify_queue): + raise ConfigError("delivery.mergify_queue must be a non-empty command-safe name") + elif mergify_queue is not None: + raise ConfigError(f"delivery.mergify_queue requires delivery.merge = 'mergify', got {merge!r}") return merge, mergify_queue @@ -298,7 +290,7 @@ def _host_paths(label: str, value: list[Any]) -> tuple[str, ...]: if not raw.startswith("/"): raise ConfigError(f"{label} entries must be absolute, got {raw!r}") path = Path(raw).resolve() - if str(path) in FORBIDDEN_RO or any( + if str(path) in ("/", "/home") or any( path.is_relative_to(tree) for tree in FORBIDDEN_RO_TREES ): raise ConfigError(f"{label} must not expose {raw!r} (host sockets or secrets)") @@ -319,8 +311,7 @@ def _env_table(table: dict[str, Any]) -> tuple[tuple[str, str], ...]: def _limits(table: dict[str, Any]) -> ResourceLimits: defaults = ResourceLimits() _reject_unknown("checks.limits", table, defaults.__dict__) - values = defaults.__dict__ | table - for name, value in values.items(): + for name, value in (defaults.__dict__ | table).items(): if isinstance(value, bool) or not isinstance(value, int) or value <= 0: raise ConfigError(f"checks.limits.{name} must be a positive int") - return ResourceLimits(**values) + return ResourceLimits(**table) diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 7857a18b..c003125d 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -54,10 +54,9 @@ def review_projection(review: dict, head: str, repo: str, number: int): if not positions: return False, None try: - if positions != [1] or len(span.encode("utf-8")) > runners.CODEX_HEADER_LIMIT: - return True, None - if len(block) > 2 and (len(block) != 3 or not re.fullmatch( - r"", block[2])): + if (positions != [1] or len(span.encode("utf-8")) > runners.CODEX_HEADER_LIMIT + or (len(block) > 2 and (len(block) != 3 or not re.fullmatch( + r"", block[2])))): return True, None marker = REVIEW_MARKER_RE.fullmatch(block[0]) evidence = runners.decode_codex_evidence(block[1])