From 8da5c4bcf55ed2b1d63d3bc85f0e57d4726e4c10 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:09:20 +0100 Subject: [PATCH 1/8] Redact credentials in PR check summaries Architecture-Review: unchanged; the shared Validation renderer still projects local check receipts into the PR body. Co-Authored-By: Codex --- src/loopzero/cli.py | 5 ++--- src/loopzero/github.py | 7 +++++++ tests/test_cli.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index c77fed41..634fa84d 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -446,9 +446,8 @@ def _validation_section(wt: Path, head: str, config: Config) -> str: lines = [f"Recorded for `{recorded[:12]}`" + ("" if recorded == head else " (not current head)")] if not _check_report_matches(loaded, wt, config, head): lines[0] += " (unverified, run `loopzero check`)" - lines += [ - f"- `{r.command}`: exit {r.exit_code}" for r in results - ] or ["- (no check commands configured)"] + lines += [f"- `{github.redact_credentials(r.command)}`: exit {r.exit_code}" + for r in results] or ["- (no check commands configured)"] return "\n".join(lines) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 9ecaffd1..f5e0e03d 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -196,6 +196,13 @@ def _api_path(args: tuple[str, ...]) -> str: return "/" + path.lstrip("/") +def redact_credentials(value: str) -> str: + value = re.sub(r"""(?i)(https?://)[^\s/?#'"<>`]+@""", r"\1[REDACTED]@", value) + return re.sub(r"""(?i)((?P['"])?\bauthorization[ \t]*:[ \t]*)""" + r"""(?(quote)(?:(?!(?P=quote))[^\r\n])+|(?:(?:basic|bearer|token)\s+)?[^\s'"`]+)""", + r"\1[REDACTED]", value) + + def _redact_tokens(value: str, token: str = "") -> str: for secret in (token, os.environ.get("GH_TOKEN", ""), os.environ.get("GITHUB_TOKEN", "")): diff --git a/tests/test_cli.py b/tests/test_cli.py index e76013e8..eee8d9fa 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -887,6 +887,37 @@ def test_pr_pushes_and_creates_draft( assert "- `echo ok`: exit 0" in body and "- `test -f README.md`: exit 0" in body +@pytest.mark.parametrize("refresh", [False, True]) +def test_pr_validation_redacts_private_check_commands(wt, gh, capsys, tmp_path, refresh): + command = ("git ls-remote 'https://x-access-token:ghs_FAKE0123@example.invalid/repo.git' " + "&& curl -H 'Authorization: Bearer opaque-fake-header' https://example.invalid/") + private = tmp_path / "private.toml" + private.write_text(WORKFLOW.replace(json.dumps("echo ok"), json.dumps(command))) + cfg = config.load(private) + head = head_of(wt) + results = (CheckResult(command, 7, 0.1, ""), CheckResult("test -f README.md", 0, 0.1, "")) + cli._save_report(wt, CheckReport(head, False, results, cli.sandbox.settings_fingerprint(cfg, wt))) + + if refresh: + git(wt, "push", "-q", "-u", "origin", "lz/t1") + gh.respond_pr_list([pr_json(headRefOid=head)]) + gh.respond(f"api repos/{REPO}/pulls/7 --method PATCH", {}) + cli._refresh_pr_checks(wt, cfg) + else: + gh.respond(branch_history_key(), []) + gh.respond_pr_list([]) + gh.respond_pr_create(pr_json(headRefOid=head)) + assert run(capsys, "--config", str(private), "pr")[0] == 0 + + body = json.loads(gh.calls[-1]["--input"])["body"] + assert "ghs_FAKE0123" not in body and "opaque-fake-header" not in body + assert "git ls-remote 'https://[REDACTED]@example.invalid/repo.git'" in body + assert "curl -H 'Authorization: [REDACTED]' https://example.invalid/`: exit 7" in body + assert f"Recorded for `{head[:12]}`" in body and "(unverified" not in body + assert "- `test -f README.md`: exit 0" in body + assert cli._load_report(wt).results == results + + @pytest.mark.parametrize("duplicate", [None, "CLOSED", "OPEN"]) def test_pr_refuses_completed_branch_before_any_publication( wt: Path, gh: FakeGh, fake_tool, tmp_path: Path, capsys, duplicate: str | None, From aaa18e347b454d168dda834eeee7bfb380135617 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:21:24 +0100 Subject: [PATCH 2/8] Redact quoted and escaped Authorization values Architecture-Review: unchanged; Validation rendering owns redaction for both GitHub publication paths. Co-Authored-By: Codex --- src/loopzero/github.py | 4 +++- tests/test_cli.py | 19 ++++++++++++++++--- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index f5e0e03d..a89ab63e 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -198,8 +198,10 @@ def _api_path(args: tuple[str, ...]) -> str: def redact_credentials(value: str) -> str: value = re.sub(r"""(?i)(https?://)[^\s/?#'"<>`]+@""", r"\1[REDACTED]@", value) + value = re.sub(r"""(?i)(\bauthorization(?:\\?['"])?[ \t]*:[ \t]*)(\\?['"])(?:(?!\2)(?:\\.|[^\\\r\n]))+\2""", + r"\1\2[REDACTED]\2", value) return re.sub(r"""(?i)((?P['"])?\bauthorization[ \t]*:[ \t]*)""" - r"""(?(quote)(?:(?!(?P=quote))[^\r\n])+|(?:(?:basic|bearer|token)\s+)?[^\s'"`]+)""", + r"""(?(quote)(?:\\.|(?!(?P=quote))[^\\\r\n])+|(?:[a-z][\w-]*[ \t]+)?(?:\\.|[^\\\s'"`])+)""", r"\1[REDACTED]", value) diff --git a/tests/test_cli.py b/tests/test_cli.py index eee8d9fa..abaf9852 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -889,8 +889,16 @@ def test_pr_pushes_and_creates_draft( @pytest.mark.parametrize("refresh", [False, True]) def test_pr_validation_redacts_private_check_commands(wt, gh, capsys, tmp_path, refresh): - command = ("git ls-remote 'https://x-access-token:ghs_FAKE0123@example.invalid/repo.git' " - "&& curl -H 'Authorization: Bearer opaque-fake-header' https://example.invalid/") + command = ( + "git ls-remote 'https://x-access-token:ghs_FAKE0123@example.invalid/repo.git' " + "&& curl -H 'Authorization: Bearer opaque-fake-header' https://example.invalid/ " + r"&& curl -H Authorization:\ Bot\ opaque-fake-header https://example.invalid/ " + """&& curl -d '{"Authorization": "Bearer opaque-fake-header"}' https://example.invalid/ """ + r'''&& curl -d "{\"Authorization\": \"Bearer opaque-fake-header\"}" https://example.invalid/ ''' + """&& python -c "request(headers={'Authorization': 'Basic opaque-fake-header'})" """ + """&& curl -H 'Authorization: Digest username="fake-user", response="opaque-fake-header"' """ + "https://example.invalid/" + ) private = tmp_path / "private.toml" private.write_text(WORKFLOW.replace(json.dumps("echo ok"), json.dumps(command))) cfg = config.load(private) @@ -912,7 +920,12 @@ def test_pr_validation_redacts_private_check_commands(wt, gh, capsys, tmp_path, body = json.loads(gh.calls[-1]["--input"])["body"] assert "ghs_FAKE0123" not in body and "opaque-fake-header" not in body assert "git ls-remote 'https://[REDACTED]@example.invalid/repo.git'" in body - assert "curl -H 'Authorization: [REDACTED]' https://example.invalid/`: exit 7" in body + assert "curl -H 'Authorization: [REDACTED]' https://example.invalid/" in body + assert "curl -H Authorization:[REDACTED] https://example.invalid/" in body + assert """curl -d '{"Authorization": "[REDACTED]"}' https://example.invalid/""" in body + assert r'''curl -d "{\"Authorization\": \"[REDACTED]\"}" https://example.invalid/''' in body + assert """python -c "request(headers={'Authorization': '[REDACTED]'})" """ in body + assert "'Authorization: [REDACTED]' https://example.invalid/`: exit 7" in body assert f"Recorded for `{head[:12]}`" in body and "(unverified" not in body assert "- `test -f README.md`: exit 0" in body assert cli._load_report(wt).results == results From 0f7ff4f8b8b3edf8f2b1408cea0db8215f755a0e Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:25:57 +0100 Subject: [PATCH 3/8] Reject whitespace-only local check commands Architecture-Review: unchanged; the existing workflow loader rejects invalid commands before stage execution. Co-Authored-By: Codex --- src/loopzero/config.py | 9 ++++++++- tests/test_config.py | 5 +++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/loopzero/config.py b/src/loopzero/config.py index 508ac7a9..cc1ca931 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -193,7 +193,7 @@ def _build(data: dict[str, Any]) -> Config: ) review[family] = ReviewConfig(table.get("model"), table.get("effort"), allowed) - commands = _strings("checks.commands", checks.get("commands", [])) + commands = _commands(checks.get("commands", [])) kwargs: dict[str, Any] = {} if "runner" in checks: runner = _strings("checks.runner", checks["runner"]) @@ -272,6 +272,13 @@ def _reject_unknown(where: str, table: dict[str, Any], allowed: Any) -> None: raise ConfigError(f"unknown key(s) in {where}: {', '.join(unknown)}") +def _commands(value: list[Any]) -> tuple[str, ...]: + commands = _strings("checks.commands", value) + if any(not command.strip() for command in commands): + raise ConfigError("checks.commands entries must each be a nonblank command") + return commands + + def _strings(label: str, value: list[Any]) -> tuple[str, ...]: if not isinstance(value, list) or not all(isinstance(item, str) and item for item in value): raise ConfigError(f"{label} must be a list of non-empty strings") diff --git a/tests/test_config.py b/tests/test_config.py index 509855bf..a877a3db 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -60,6 +60,9 @@ def test_load_full_config(tmp_path): limits=ResourceLimits(memory_mb=1024, file_mb=512), ) + padded = FULL.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')) @@ -112,6 +115,8 @@ def test_invalid_toml(tmp_path): ('[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]\nreviewers = ["gpt"]\n', "delivery.reviewers entries"), From 3b649d6fe937c2c1b6fc51f2bf3cee543c44999a Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:35:21 +0100 Subject: [PATCH 4/8] Stream local check output into a bounded diagnostic tail Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 4 +-- src/loopzero/_proc.py | 52 +++++++++++++++++++++++++++++++++++- src/loopzero/sandbox.py | 1 + tests/test_sandbox.py | 59 ++++++++++++++++++++++++++++++----------- 4 files changed, 97 insertions(+), 19 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bfe286f2..0d0471bc 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -76,8 +76,8 @@ The [CLI](../src/loopzero/cli.py) implements the contract's 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. diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index 31e63dfa..31b3dfe3 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -2,7 +2,10 @@ from __future__ import annotations +import codecs +import io import os +import selectors import signal import subprocess import time @@ -55,6 +58,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], *, @@ -66,6 +108,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. @@ -74,8 +117,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" @@ -94,7 +141,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): diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index a358d56f..6fd7b21d 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -460,6 +460,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, diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 5e805278..d558ed5d 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -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 @@ -108,9 +110,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() @@ -231,26 +234,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): From 0cac29763ea42e91d4199554a09c44d3c0327984 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:24:43 +0100 Subject: [PATCH 5/8] Run checks fresh when declared inputs match no files Architecture-Review: unchanged; stage reuse still depends on a Git and checkout fingerprint, now unavailable for unmatched pathspecs. Co-Authored-By: Codex --- src/loopzero/cli.py | 3 ++- src/loopzero/sandbox.py | 31 +++++++++++++++++++++++-------- tests/test_sandbox.py | 17 +++++++++++++++++ 3 files changed, 42 insertions(+), 9 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 46a93e29..cafd980b 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -598,7 +598,8 @@ def cmd_check(args: argparse.Namespace) -> int: report = sandbox.run_checks(config, wt, progress=lambda command: print( f"running: {command}", flush=True), status=lambda message: print(message, flush=True), - checkpoint=lambda partial: _save_report(wt, partial)) + checkpoint=lambda partial: _save_report(wt, partial), + workflow=args.config or f"origin/{config.base_branch}:workflow.toml") except sandbox.SandboxUnavailable as exc: print(f"sandbox unavailable: {exc}", file=sys.stderr) return 2 diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index a358d56f..a5c8d330 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -130,7 +130,7 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO progress: Callable[[str], None] | None = None, status: Callable[[str], None] | None = None, checkpoint: Callable[[CheckReport], None] | None = None, - _resolved: bool = False) -> CheckReport: + workflow: str | Path = "workflow.toml", _resolved: bool = False) -> CheckReport: """Run checks, stopping at the first failure; status emits only stage metadata. progress receives each command before launch, as before. Optional status receives @@ -179,7 +179,8 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO for index, command in enumerate(commands): if progress: progress(command) - key = _input_key(config, worktree, command, base) if not dirty else None + key = _input_key(config, worktree, command, base, status=status, + workflow=workflow) if not dirty else None old = previous.get(command) if key and old and old.input_key == key: result = old @@ -303,19 +304,33 @@ def settings_fingerprint(config: Config, worktree: Path, *, base: str | None = N return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() -def _input_key(config: Config, worktree: Path, command: str, base: str) -> str | None: - if not base or (command not in config.inputs and "." not in config.inputs.get("*", ())): - return None - paths = (*config.inputs.get(command, ()), *config.inputs.get("*", ())) +def _input_blobs(config: Config, worktree: Path, paths: tuple[str, ...]) -> str | None: # Empty pathspecs must not accidentally mean the whole tree. + if not paths: + return "" empty = _git(config, worktree, "hash-object", "-t", "tree", "/dev/null").strip() try: - blobs = _git(config, worktree, "-c", "core.quotePath=true", "diff-tree", "--no-commit-id", - "--raw", "-r", "--no-abbrev", empty, "HEAD", "--", *paths) if paths else "" + return _git(config, worktree, "-c", "core.quotePath=true", "diff-tree", "--no-commit-id", + "--raw", "-r", "--no-abbrev", empty, "HEAD", "--", *paths) except OSError as exc: if exc.errno == errno.E2BIG: return None raise + + +def _input_key(config: Config, worktree: Path, command: str, base: str, *, + status: Callable[[str], None] | None = None, + workflow: str | Path = "workflow.toml") -> str | None: + if not base or (command not in config.inputs and "." not in config.inputs.get("*", ())): + return None + paths = (*config.inputs.get(command, ()), *config.inputs.get("*", ())) + blobs = _input_blobs(config, worktree, paths) + if not blobs: + if blobs == "" and status: + entry = command if command in config.inputs else "*" + status(f"{workflow}: checks.inputs[{entry!r}] matches no tracked files. " + f"Correct the pathspecs {paths!r}. Running the check fresh.") + return None contents = [] root = worktree.resolve() try: diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 5e805278..a0ad0fe8 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -771,6 +771,23 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch assert report.head == git(git_repo, 'rev-parse', 'HEAD').strip() +@pytest.mark.parametrize("paths", [("ipnut.txt",), ()]) +def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, paths): + (git_repo / ".git/info/exclude").write_text(".loopzero/\n") + command = 'test "$(cat README.md)" = hello' + config = make_config(checks=(command,), inputs={command: paths}) + first = sandbox.run_checks(config, git_repo) + assert first.ok + _save_report(git_repo, first) + (git_repo / "README.md").write_text("fail\n") + git(git_repo, "commit", "-qam", "change actual input") + + result = sandbox.run_checks(config, git_repo, status=(messages := []).append) + assert result.results[0].exit_code == 1 + assert any("workflow.toml: checks.inputs" in message and repr(paths) in message + for message in messages) + + def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_base): (git_repo / ".git/info/exclude").write_text(".loopzero/\n") path = git_repo / "README.md" From 084c7469f0c5bb37b9edb1422cdfe562ea9edc29 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:32:02 +0100 Subject: [PATCH 6/8] Report unmatched inputs even when reuse is unavailable Architecture-Review: unchanged; execution still runs fresh when stage reuse is unavailable. Co-Authored-By: Codex --- src/loopzero/sandbox.py | 23 +++++++++++++---------- tests/test_sandbox.py | 10 +++++++--- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index a5c8d330..afa65d61 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -179,8 +179,8 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO for index, command in enumerate(commands): if progress: progress(command) - key = _input_key(config, worktree, command, base, status=status, - workflow=workflow) if not dirty else None + key = _input_key(config, worktree, command, "" if dirty else base, + status=status, workflow=workflow) old = previous.get(command) if key and old and old.input_key == key: result = old @@ -321,16 +321,19 @@ def _input_blobs(config: Config, worktree: Path, paths: tuple[str, ...]) -> str def _input_key(config: Config, worktree: Path, command: str, base: str, *, status: Callable[[str], None] | None = None, workflow: str | Path = "workflow.toml") -> str | None: - if not base or (command not in config.inputs and "." not in config.inputs.get("*", ())): + if command not in config.inputs and "." not in config.inputs.get("*", ()): return None - paths = (*config.inputs.get(command, ()), *config.inputs.get("*", ())) - blobs = _input_blobs(config, worktree, paths) - if not blobs: - if blobs == "" and status: - entry = command if command in config.inputs else "*" - status(f"{workflow}: checks.inputs[{entry!r}] matches no tracked files. " - f"Correct the pathspecs {paths!r}. Running the check fresh.") + entries = {key: config.inputs[key] for key in (command, "*") if key in config.inputs} + blobs = _input_blobs(config, worktree, tuple(path for paths in entries.values() for path in paths)) + if blobs == "" and status: + status(f"{workflow}: checks.inputs for {command!r} matches no tracked files. " + f"Correct these entries: {entries!r}. Running the check fresh.") + if not blobs or not base: return None + return _hash_inputs(config, worktree, command, base, blobs) + + +def _hash_inputs(config: Config, worktree: Path, command: str, base: str, blobs: str) -> str | None: contents = [] root = worktree.resolve() try: diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index a0ad0fe8..b2d0362c 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -771,16 +771,20 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch assert report.head == git(git_repo, 'rev-parse', 'HEAD').strip() -@pytest.mark.parametrize("paths", [("ipnut.txt",), ()]) -def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, paths): +@pytest.mark.parametrize("case", ["typo", "empty", "dirty", "no_base"]) +def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, case): (git_repo / ".git/info/exclude").write_text(".loopzero/\n") command = 'test "$(cat README.md)" = hello' + paths = () if case == "empty" else ("ipnut.txt",) config = make_config(checks=(command,), inputs={command: paths}) first = sandbox.run_checks(config, git_repo) assert first.ok _save_report(git_repo, first) (git_repo / "README.md").write_text("fail\n") - git(git_repo, "commit", "-qam", "change actual input") + if case != "dirty": + git(git_repo, "commit", "-qam", "change actual input") + if case == "no_base": + git(git_repo, "update-ref", "-d", "refs/remotes/origin/main") result = sandbox.run_checks(config, git_repo, status=(messages := []).append) assert result.results[0].exit_code == 1 From ac15e09ec2e9debbc79fbbf5472904433fd79640 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:35:04 +0100 Subject: [PATCH 7/8] Keep diagnostic lookup failures from blocking fresh stages Co-Authored-By: Codex --- src/loopzero/sandbox.py | 11 +++++++++-- tests/test_sandbox.py | 8 ++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index afa65d61..bfcb121d 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -323,10 +323,17 @@ def _input_key(config: Config, worktree: Path, command: str, base: str, *, workflow: str | Path = "workflow.toml") -> str | None: if command not in config.inputs and "." not in config.inputs.get("*", ()): return None + if not base and status is None: + return None entries = {key: config.inputs[key] for key in (command, "*") if key in config.inputs} - blobs = _input_blobs(config, worktree, tuple(path for paths in entries.values() for path in paths)) + try: + blobs = _input_blobs(config, worktree, tuple(path for paths in entries.values() for path in paths)) + except (SandboxUnavailable, OSError): + if not base: + return None + raise if blobs == "" and status: - status(f"{workflow}: checks.inputs for {command!r} matches no tracked files. " + status(f"{workflow}: checks.inputs for {command!r} matches no files in HEAD. " f"Correct these entries: {entries!r}. Running the check fresh.") if not blobs or not base: return None diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index b2d0362c..de42feab 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -792,6 +792,14 @@ def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, case): for message in messages) +def test_input_diagnostic_failure_does_not_block_dirty_check(git_repo, bwrap_log, fetched_base): + (git_repo / "README.md").write_text("dirty\n") + command = 'test "$(cat README.md)" = dirty' + config = make_config(checks=(command,), inputs={command: (":(bogus)README.md",)}) + report = sandbox.run_checks(config, git_repo, status=lambda _: None) + assert report.ok and report.dirty and report.results[0].command == command + + def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_base): (git_repo / ".git/info/exclude").write_text(".loopzero/\n") path = git_repo / "README.md" From abd4c709c6a2d3dd65a72be04441488e3dff17ab Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:40:25 +0100 Subject: [PATCH 8/8] Keep timeout and invalid argument diagnostics from blocking checks Co-Authored-By: Codex --- src/loopzero/sandbox.py | 2 +- tests/test_sandbox.py | 12 ++++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index bfcb121d..4a0df20f 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -328,7 +328,7 @@ def _input_key(config: Config, worktree: Path, command: str, base: str, *, entries = {key: config.inputs[key] for key in (command, "*") if key in config.inputs} try: blobs = _input_blobs(config, worktree, tuple(path for paths in entries.values() for path in paths)) - except (SandboxUnavailable, OSError): + except (SandboxUnavailable, _proc.ProcTimeout, OSError, ValueError): if not base: return None raise diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index de42feab..e660ee74 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -792,10 +792,18 @@ def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, case): for message in messages) -def test_input_diagnostic_failure_does_not_block_dirty_check(git_repo, bwrap_log, fetched_base): +@pytest.mark.parametrize("path", [":(bogus)README.md", "README\0.md", "README.md"]) +def test_input_diagnostic_failure_does_not_block_dirty_check( + git_repo, bwrap_log, fetched_base, monkeypatch, path, +): + if path == "README.md": + def timed_out(*args): + raise sandbox._proc.ProcTimeout("input lookup timed out") + + monkeypatch.setattr(sandbox, "_input_blobs", timed_out) (git_repo / "README.md").write_text("dirty\n") command = 'test "$(cat README.md)" = dirty' - config = make_config(checks=(command,), inputs={command: (":(bogus)README.md",)}) + config = make_config(checks=(command,), inputs={command: (path,)}) report = sandbox.run_checks(config, git_repo, status=lambda _: None) assert report.ok and report.dirty and report.results[0].command == command