diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c474e6e7..b5424863 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -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 +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. diff --git a/pyproject.toml b/pyproject.toml index 31b6268a..9dd9780b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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"] diff --git a/scripts/check_architecture_docs.py b/scripts/check_architecture_docs.py index c7147cb0..6d78847d 100644 --- a/scripts/check_architecture_docs.py +++ b/scripts/check_architecture_docs.py @@ -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"}, } diff --git a/src/loopzero/_cli_args.py b/src/loopzero/_cli_args.py new file mode 100644 index 00000000..ce9af047 --- /dev/null +++ b/src/loopzero/_cli_args.py @@ -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 ") + 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 [ ""]', + 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 [ ""] 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 diff --git a/src/loopzero/_cli_entry.py b/src/loopzero/_cli_entry.py new file mode 100644 index 00000000..b7df2391 --- /dev/null +++ b/src/loopzero/_cli_entry.py @@ -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) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 48a64159..1a461466 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -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) + import argparse import dataclasses import fcntl import hashlib -import importlib.metadata -import io import json -import math import os import shlex import random @@ -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 @@ -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 ") - 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 [ ""]', - 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 [ ""] 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 @@ -1845,4 +1770,4 @@ def _one_line(exc: BaseException) -> str: if __name__ == "__main__": - sys.exit(main()) + sys.exit(_run(_module_args)) diff --git a/tach.toml b/tach.toml index 442c5302..58b5df60 100644 --- a/tach.toml +++ b/tach.toml @@ -69,6 +69,7 @@ depends_on = [ [[modules]] path = "loopzero.cli" depends_on = [ + "loopzero._cli_args", "loopzero._proc", "loopzero.config", "loopzero.eligibility", @@ -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"] diff --git a/tests/test_architecture_docs.py b/tests/test_architecture_docs.py index 5be3231f..25410cee 100644 --- a/tests/test_architecture_docs.py +++ b/tests/test_architecture_docs.py @@ -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", ".") diff --git a/tests/test_cli.py b/tests/test_cli.py index b5536583..93458e3d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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"] @@ -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): + 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: