Skip to content
Merged
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
3 changes: 2 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ a new persistent store.

## Delivery and feedback

The [CLI](../src/loopzero/cli.py) implements the contract's
The [console entry point](../src/loopzero/_cli_entry.py) parses arguments before
Comment thread
eowca marked this conversation as resolved.
Resolved
loading the delivery [commands](../src/loopzero/cli.py), which implement the contract's
[six steps](../core/CONTRACT.md#the-six-steps):

1. `start` creates an isolated worktree and task branch from the configured base.
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ version = "2.0.0a0"
dependencies = ["PyYAML==6.0.3"]

[project.scripts]
loopzero = "loopzero.cli:main"
loopzero = "loopzero._cli_entry:main"

[build-system]
requires = ["hatchling==1.33.0"]
Expand Down
2 changes: 1 addition & 1 deletion scripts/check_architecture_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
}
# Compare selected owning interfaces rather than requiring doc churn for every bug fix.
INTERFACES = {
"src/loopzero/cli.py": {"build_parser"},
"src/loopzero/_cli_args.py": {"build_parser", "WAIT_TIMEOUT"},
"src/loopzero/config.py": {"_SECTIONS", "MERGE_STRATEGIES", "REVIEWER_FAMILIES"},
"src/loopzero/types.py": {"Config", "ResourceLimits", "ReviewConfig"},
}
Expand Down
103 changes: 103 additions & 0 deletions src/loopzero/_cli_args.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
"""Argument parsing shared by the console script and CLI module."""

from __future__ import annotations

import argparse
import io
import sys

WAIT_TIMEOUT = 1800.0


def _wait_seconds(value: str) -> float:
from math import isfinite

try:
seconds = float(value)
if isfinite(seconds) and seconds >= 0:
return seconds
except ValueError:
pass
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)"
)
parser.add_argument("--version", action=_VersionAction, nargs=0, help="show program's version number and exit")
sub = parser.add_subparsers(dest="command", required=True)
start = sub.add_parser("start", help="create an owned worktree and branch for <slug>")
start.add_argument("slug")
sub.add_parser("check", help="run the configured checks in the sandbox")
sub.add_parser("pr", help="push and open or refresh the draft PR")
review = sub.add_parser("review", help="run native review and post one canonical review")
review.add_argument(
"--repost", action="store_true", help="post the saved review for HEAD without a model"
)
review.add_argument("--model", help="reviewer model override for a fresh review")
review.add_argument("--effort", help="reviewer effort override for a fresh review")
ready = sub.add_parser(
"ready", help="compute readiness and mark the PR ready; --wait polls required checks"
)
merge = sub.add_parser(
"merge", help="recheck readiness, merge and clean up; --wait waits for checks and landing"
)
for waiter, what in ((ready, "required checks on this head"), (merge, "required checks and the landed merge")):
waiter.add_argument(
"--wait", nargs="?", const=WAIT_TIMEOUT, type=_wait_seconds, metavar="SECONDS",
help=f"wait for {what} (default {WAIT_TIMEOUT:.0f}s); exit 3 on timeout",
)
merge.add_argument(
"--cancel", action="store_true", help="request removal from the configured Mergify queue"
)
resolve = sub.add_parser(
"resolve", usage='%(prog)s [<finding-id> "<reply>"]',
help="list open findings, or reply to one and resolve it",
)
resolve.add_argument("finding", nargs="?", help="finding id from the list (8 hex digits)")
resolve.add_argument("reply", nargs="?", default="", help="what changed, e.g. the fix commit")
sub.add_parser("status", help="show where this branch is in the sequence")
return parser


def _version() -> str:
"""Package version plus the pinned source revision when installed from Git."""
import json
from importlib.metadata import distribution

dist = distribution("loopzero")
try:
commit = json.loads(dist.read_text("direct_url.json") or "{}")["vcs_info"]["commit_id"]
except (KeyError, TypeError, json.JSONDecodeError):
commit = "unknown revision (not installed from a Git URL)"
return f"loopzero {dist.version} {commit}"


class _VersionAction(argparse.Action):
def __call__(self, parser, _namespace, _values, _option_string=None):
print(_version())
parser.exit()


def parse_args(parser: argparse.ArgumentParser, argv: list[str] | None) -> argparse.Namespace:
# Progress lines must precede the stderr verdict when both go to one file.
if isinstance(sys.stdout, io.TextIOWrapper):
sys.stdout.reconfigure(line_buffering=True)
args = parser.parse_args(argv)
if args.command == "resolve" and args.finding is not None and not args.reply.strip():
parser.error('expected resolve [<finding-id> "<reply>"] with a nonblank reply for a finding')
if args.command == "review" and args.repost:
conflicts = [f"--{name}" for name in ("model", "effort") if getattr(args, name) is not None]
if conflicts:
parser.error(f"review --repost cannot be combined with {' or '.join(conflicts)}")
return args
10 changes: 10 additions & 0 deletions src/loopzero/_cli_entry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""Console entry point. Load delivery commands only after parsing."""

from loopzero._cli_args import build_parser, parse_args


def main(argv: list[str] | None = None) -> int:
args = parse_args(build_parser(), argv)
from loopzero.cli import _run

return _run(args)
99 changes: 12 additions & 87 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@

from __future__ import annotations

from loopzero._cli_args import build_parser, parse_args

# Module execution parses help and version before loading delivery code.
if __name__ == "__main__":
_module_args = parse_args(build_parser(), None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: python -m loopzero.cli parses argv twice; _module_args is never used

Under -m, line 9 parses argv into _module_args, and nothing reads it. The if __name__ == "__main__": sys.exit(main()) block at line 1773 then calls main(), which runs build_parser() and parse_args() again, including the stdout reconfigure and the validation. Output stays the same, but this is a dead variable plus duplicated parsing, and the two entry paths can drift apart. Smallest fix: make the bottom block sys.exit(_run(_module_args)), which removes the second parse and gives the early parse a reader.


import argparse
import dataclasses
import fcntl
import hashlib
import importlib.metadata
import io
import json
import math
import os
import shlex
import random
Expand Down Expand Up @@ -37,7 +40,7 @@
# --wait: poll interval, default timeout, and how long a required check may stay
# missing before GitHub is assumed to have dropped the event for this head.
# Each poll costs several GitHub API calls from a quota shared by every session.
WAIT_INTERVAL, WAIT_TIMEOUT, MISSING_RUN_GRACE = 30.0, 1800.0, 120.0
WAIT_INTERVAL, MISSING_RUN_GRACE = 30.0, 120.0
STALE_VERDICT_GRACE, MAX_REVIEW_CLOCK_SKEW = 900.0, 30.0
PUSH_TIMEOUT = 600.0 # consumer pre-push hooks (lint, tests) routinely exceed GIT_TIMEOUT
NEXT_WAIT = "next: loopzero ready --wait" # named at the moment of need; agents hand-roll polls otherwise
Expand Down Expand Up @@ -1739,92 +1742,14 @@ def _print_mergify_status(config: Config, pr: github.PR, readiness: github.Readi
# --------------------------------------------------------------------------- entry point


def _wait_seconds(value: str) -> float:
try:
seconds = float(value)
if math.isfinite(seconds) and seconds >= 0:
return seconds
except ValueError:
pass
raise argparse.ArgumentTypeError("expected a finite, nonnegative number of seconds")


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=Path, default=None, help="path to workflow.toml (default: repo root)"
)
parser.add_argument("--version", action="version", version=_version())
sub = parser.add_subparsers(dest="command", required=True)
start = sub.add_parser("start", help="create an owned worktree and branch for <slug>")
start.add_argument("slug")
start.set_defaults(func=cmd_start)
sub.add_parser("check", help="run the configured checks in the sandbox").set_defaults(
func=cmd_check
)
sub.add_parser("pr", help="push and open or refresh the draft PR").set_defaults(func=cmd_pr)
review = sub.add_parser("review", help="run native review and post one canonical review")
review.add_argument(
"--repost", action="store_true", help="post the saved review for HEAD without a model"
)
review.add_argument("--model", help="reviewer model override for a fresh review")
review.add_argument("--effort", help="reviewer effort override for a fresh review")
review.set_defaults(func=cmd_review)
ready = sub.add_parser(
"ready", help="compute readiness and mark the PR ready; --wait polls required checks"
)
merge = sub.add_parser(
"merge", help="recheck readiness, merge and clean up; --wait waits for checks and landing"
)
for waiter, what in ((ready, "required checks on this head"), (merge, "required checks and the landed merge")):
waiter.add_argument(
"--wait", nargs="?", const=WAIT_TIMEOUT, type=_wait_seconds, metavar="SECONDS",
help=f"wait for {what} (default {WAIT_TIMEOUT:.0f}s); exit 3 on timeout",
)
merge.add_argument(
"--cancel", action="store_true", help="request removal from the configured Mergify queue"
)
ready.set_defaults(func=cmd_ready)
merge.set_defaults(func=cmd_merge)
resolve = sub.add_parser(
"resolve", usage='%(prog)s [<finding-id> "<reply>"]',
help="list open findings, or reply to one and resolve it",
)
resolve.add_argument("finding", nargs="?", help="finding id from the list (8 hex digits)")
resolve.add_argument("reply", nargs="?", default="", help="what changed, e.g. the fix commit")
resolve.set_defaults(func=cmd_resolve)
status = sub.add_parser("status", help="show where this branch is in the sequence")
status.set_defaults(func=cmd_status)
return parser


def _version() -> str:
"""Package version plus the pinned source revision when installed from Git."""
dist = importlib.metadata.distribution("loopzero")
try:
commit = json.loads(dist.read_text("direct_url.json") or "{}")["vcs_info"]["commit_id"]
except (KeyError, TypeError, json.JSONDecodeError):
commit = "unknown revision (not installed from a Git URL)"
return f"loopzero {dist.version} {commit}"
def main(argv: list[str] | None = None) -> int:
return _run(parse_args(build_parser(), argv))


def main(argv: list[str] | None = None) -> int:
# Progress lines must precede the stderr verdict when both go to one file.
if isinstance(sys.stdout, io.TextIOWrapper):
sys.stdout.reconfigure(line_buffering=True)
parser = build_parser()
args = parser.parse_args(argv)
if args.command == "resolve" and args.finding is not None and not args.reply.strip():
parser.error('expected resolve [<finding-id> "<reply>"] with a nonblank reply for a finding')
if args.command == "review" and args.repost:
conflicts = [f"--{name}" for name in ("model", "effort") if getattr(args, name) is not None]
if conflicts:
parser.error(f"review --repost cannot be combined with {' or '.join(conflicts)}")
def _run(args: argparse.Namespace) -> int:
try:
with _proc.unwind_on_sigterm():
return args.func(args)
return globals()[f"cmd_{args.command}"](args)
except IndependentReviewerUnavailable as exc:
print(f"loopzero {args.command}: {exc}", file=sys.stderr)
return 4
Expand All @@ -1845,4 +1770,4 @@ def _one_line(exc: BaseException) -> str:


if __name__ == "__main__":
sys.exit(main())
sys.exit(_run(_module_args))
9 changes: 9 additions & 0 deletions tach.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ depends_on = [
[[modules]]
path = "loopzero.cli"
depends_on = [
"loopzero._cli_args",
"loopzero._proc",
"loopzero.config",
"loopzero.eligibility",
Expand All @@ -79,3 +80,11 @@ depends_on = [
"loopzero.types",
"loopzero.worktree",
]

[[modules]]
path = "loopzero._cli_args"
depends_on = []

[[modules]]
path = "loopzero._cli_entry"
depends_on = ["loopzero._cli_args", "loopzero.cli"]
2 changes: 1 addition & 1 deletion tests/test_architecture_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def test_broken_local_link_fails_even_with_guide_update(git_repo, target):

def test_private_code_fix_needs_no_pointless_documentation_edit(git_repo):
base = prepare(git_repo)
path = git_repo / "src/loopzero/cli.py"
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")
git(git_repo, "add", ".")
Expand Down
18 changes: 9 additions & 9 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1123,10 +1123,9 @@ def test_pr_accepts_angle_brackets_and_sublists_as_filled_text(wt: Path) -> None


def test_progress_output_precedes_the_stderr_verdict_in_one_file(tmp_path: Path) -> None:
script = ("import argparse, sys\nfrom loopzero import cli\np = argparse.ArgumentParser()\n"
"def wait(args):\n print('waiting')\n raise cli.CliError('dequeued')\n"
"p.set_defaults(func=wait, command='merge')\ncli.build_parser = lambda: p\n"
"sys.exit(cli.main([]))\n")
script = ("import sys\nfrom loopzero import cli\ndef wait(args):\n"
" print('waiting')\n raise cli.CliError('dequeued')\n"
"cli.cmd_merge = wait\nsys.exit(cli.main(['merge']))\n")
with (tmp_path / "log").open("w") as log:
subprocess.run([sys.executable, "-c", script], stdout=log, stderr=subprocess.STDOUT, check=False)
assert (tmp_path / "log").read_text().splitlines() == ["waiting", "loopzero merge: dequeued"]
Expand Down Expand Up @@ -1259,11 +1258,12 @@ def test_pr_refuses_to_overwrite_a_pr_head_it_has_never_seen(
assert git(origin, "rev-parse", "refs/heads/lz/t1").strip() == pushed


def test_version_names_the_installed_revision(capsys) -> None:
with pytest.raises(SystemExit) as stop:
cli.main(["--version"])
out = capsys.readouterr().out
assert stop.value.code == 0 and re.fullmatch(r"loopzero \S+ .+\n", out), out
@pytest.mark.parametrize("flag, pattern", [("--version", r"loopzero \S+ .+\n\Z"), ("--help", r"usage: loopzero ")])
def test_cli_info_leaves_delivery_backends_unloaded(flag, pattern):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Nothing tests the console-script entry point (loopzero._cli_entry:main)

Acceptance requires the console script's help and version output to stay the same and help to load no backends. The rewritten test only runs -m loopzero.cli. _cli_entry.main is the actual [project.scripts] target, and no test imports or calls it, so a regression there (for example, importing loopzero.cli at module level) would go unnoticed. You can cover it without adding test lines by having one parametrized case run -c 'import sys; from loopzero._cli_entry import main; sys.exit(main())' instead of -m loopzero.cli.

for entry in (("-m", "loopzero.cli"), ("-c", "from loopzero._cli_entry import main; main()")):
done = subprocess.run([sys.executable, "-X", "importtime", *entry, flag], capture_output=True, text=True)
assert done.returncode == 0 and re.match(pattern, done.stdout), done
assert not re.search(r"loopzero\.(github|mergify|runners|sandbox)\b", done.stderr)


def test_pr_refuses_dirty(wt: Path, gh: FakeGh, capsys) -> None:
Expand Down
Loading