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
4 changes: 2 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
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 @@ -105,6 +108,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 @@ -116,6 +158,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 @@ -124,8 +167,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 @@ -144,7 +191,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
8 changes: 4 additions & 4 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,9 +420,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 _check_report_problem(loaded, wt, config, head, require_pass=False):
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)


Expand Down Expand Up @@ -597,7 +596,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
Expand Down
9 changes: 8 additions & 1 deletion src/loopzero/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand Down Expand Up @@ -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")
Expand Down
9 changes: 9 additions & 0 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,15 @@ 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)
value = re.sub(r"""(?i)(\bauthorization(?:\\?['"])?[ \t]*:[ \t]*)(\\?['"])(?:(?!\2)(?:\\.|[^\\\r\n]))+\2""",
r"\1\2[REDACTED]\2", value)
return re.sub(r"""(?i)((?P<quote>['"])?\bauthorization[ \t]*:[ \t]*)"""
r"""(?(quote)(?:\\.|(?!(?P=quote))[^\\\r\n])+|(?:[a-z][\w-]*[ \t]+)?(?:\\.|[^\\\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", "")):
Expand Down
42 changes: 34 additions & 8 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,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
Expand Down Expand Up @@ -129,7 +129,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, "" if dirty else base,
status=status, workflow=workflow)
old = previous.get(command)
if key and old and old.input_key == key:
result = old
Expand Down Expand Up @@ -253,19 +254,43 @@ 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 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}
try:
blobs = _input_blobs(config, worktree, tuple(path for paths in entries.values() for path in paths))
except (SandboxUnavailable, _proc.ProcTimeout, OSError, ValueError):
if not base:
return None
raise
if blobs == "" and status:
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
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:
Expand Down Expand Up @@ -410,6 +435,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
44 changes: 44 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -957,6 +957,50 @@ 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/ "
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)
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/" 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


@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,
Expand Down
5 changes: 5 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
Expand Down Expand Up @@ -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"),
Expand Down
Loading
Loading