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
7 changes: 5 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,11 @@ The CLI also writes a head-bound checks receipt and saved review output in
`.loopzero/` for local readiness and reposting. They do not form a second authoritative delivery history; new Codex native audit
receipts have the restricted retention requirement described below. Local readiness requires
its current successful check receipt; hosted eligibility evaluates GitHub
review evidence using trusted base configuration. Losing local artifacts may
require rerunning checks or review, and never creates a hosted approval.
review evidence using trusted base configuration. Local readiness and merge fetch

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: Docs say the base is fetched once, but there can be two fetches

load_trusted calls _remote_workflow(..., refresh=refresh) for origin's default branch. When that workflow's repo.base names a different branch, it calls it again for that branch. So ready/merge can fetch two branches, and the default branch it fetches isn't necessarily the configured base. Also, refs/remotes/origin/HEAD is not refreshed, so the branch chosen as the policy source can still come from stale local state. Either reword the doc (e.g. "fetch origin's default branch and the configured base branch at startup") or note that origin/HEAD is taken from local state.

the configured origin base once at startup before loading its publisher policy.
A receipt bound to the base may require a new check after that base advances.
Losing local artifacts may require rerunning checks or review, and never creates
a hosted approval.
Saved runner artifacts also retain the repository, PR and actual request publisher
before publication. A lost POST reply triggers a read-only reconciliation bounded
by one 30-second transport deadline, with no read retries. Recovery regenerates
Expand Down
7 changes: 5 additions & 2 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,14 +125,15 @@ def _repo_root(wt: Path) -> Path:

def _load_config(
args: argparse.Namespace, root: Path, *, pin_checks: bool = False, previous: Config | None = None,
refresh: bool = False,
) -> Config:
path = args.config or root / "workflow.toml"
if not pin_checks:
return config_mod.load(path)
if args.config:
print("checks are unpinned because --config was provided")
return config_mod.load(path)
config = config_mod.load_trusted(root, previous=previous)
config = config_mod.load_trusted(root, previous=previous, refresh=refresh)
if args.command == "check":
if not config.checks:
raise config_mod.ConfigError(
Expand All @@ -145,7 +146,9 @@ def _load_config(

def _context(args: argparse.Namespace, *, pin_checks: bool = False) -> tuple[Path, Config]:
wt = _toplevel()
return wt, _load_config(args, wt, pin_checks=pin_checks)
return wt, _load_config(
args, wt, pin_checks=pin_checks, refresh=args.command in {"ready", "merge"},
)


def _is_ancestor(wt: Path, sha: str, head: str) -> bool:
Expand Down
19 changes: 14 additions & 5 deletions src/loopzero/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,21 @@ def _has_replacement_refs(common_dir: Path) -> bool:
return b" refs/replace/" in packed


def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tuple[Config, str]:
def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, refresh: bool) -> tuple[Config, str]:
source = f"origin/{branch}:workflow.toml"
hint = "Fetch the trusted base workflow, or supply --config for bootstrap or an override."
ref = f"refs/remotes/origin/{branch}"
if refresh:
fetched = _proc.run(
["git", "fetch", "--quiet", "--no-tags", "--no-recurse-submodules",
"--no-write-fetch-head", "origin", f"+refs/heads/{branch}:{ref}"],
cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60,
)
if fetched.exit_code != 0:
raise ConfigError(f"could not refresh origin/{branch}. {hint}")

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: Fetch failure drops git's diagnostic

When the refresh fetch fails (authentication, network, a missing remote branch or a 60s timeout that returns a non-zero exit), the user only sees could not refresh origin/<branch>. Git's stderr is thrown away, and the hint ("Fetch the trusted base workflow") doesn't say why the fetch failed. base_revision in the same file already shows the last line of stderr with _proc.tail(done.stderr or done.stdout, 1). Smallest fix: add _proc.tail(fetched.stderr or fetched.stdout, 1) to the ConfigError message. The fail-closed behaviour stays the same.

directory_args = ["--path-format=absolute", "--git-common-dir"] if previous is not None else []
resolved = _proc.run(
["git", "rev-parse", *directory_args, "--verify", f"refs/remotes/origin/{branch}^{{commit}}"],
["git", "rev-parse", *directory_args, "--verify", f"{ref}^{{commit}}"],
cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60,
)
if resolved.exit_code != 0:
Expand All @@ -140,7 +149,7 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None) -> tu
raise ConfigError(f"{source}: {exc}. {hint}") from None


def load_trusted(worktree: Path, *, previous: Config | None = None) -> Config:
def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: bool = False) -> Config:
"""Select delivery policy using Git's origin default and its trusted workflow."""
prefix = "refs/remotes/origin/"
default = _proc.run(
Expand All @@ -154,10 +163,10 @@ def load_trusted(worktree: Path, *, previous: Config | None = None) -> Config:
"or supply --config for bootstrap or an override."
)
branch = ref.removeprefix(prefix)
policy, revision = _remote_workflow(worktree, branch, previous)
policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh)
if policy.base_branch == branch:
return replace(policy, trusted_base_revision=revision)
base, revision = _remote_workflow(worktree, policy.base_branch, previous)
base, revision = _remote_workflow(worktree, policy.base_branch, previous, refresh=refresh)
if base.base_branch != policy.base_branch:
raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config")
return replace(base, trusted_base_revision=revision)
Expand Down
33 changes: 24 additions & 9 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1445,13 +1445,14 @@ def test_review_runtime_paths_use_only_verified_base(
def test_runtime_pinning_requires_trusted_workflow(
wt: Path, gh: FakeGh, fake_bin: Path, capsys, command: str, missing: str,
) -> None:
origin = Path(git(wt, "remote", "get-url", "origin").strip())
if missing == "default":
git(wt, "symbolic-ref", "--delete", "refs/remotes/origin/HEAD")
elif missing == "remote":
git(wt, "update-ref", "-d", "refs/remotes/origin/main")
else:
git(wt, "update-ref", "refs/remotes/origin/main",
git(wt, "rev-list", "--max-parents=0", "HEAD").strip())
options = ("-d",) if missing == "remote" else ()
revision = () if options else (git(wt, "rev-list", "--max-parents=0", "HEAD").strip(),)
for checkout, ref in ((wt, "refs/remotes/origin/main"), (origin, "refs/heads/main")):
git(checkout, "update-ref", *options, ref, *revision)
prepare_review(wt, gh, fake_bin)
code, out, err = run(capsys, command)
assert "reviewer paths" not in out + err
Expand Down Expand Up @@ -2151,7 +2152,7 @@ def test_ready_after_reviewed_head(
popen = subprocess.Popen

def isolated_fetch(argv, **kwargs):
if "fetch" in argv:
if "fetch" in argv and f"https://github.com/{REPO}.git" in argv:
if history == "missing history":
raise cli.eligibility.candidate.CandidateError("history unavailable")
argv = [wt.as_uri() if arg == f"https://github.com/{REPO}.git" else arg for arg in argv]
Expand Down Expand Up @@ -2192,7 +2193,7 @@ def test_ready_marks_draft_ready(wt: Path, gh: FakeGh, capsys, head, branch, git
gh.respond("pr ready", "")
git_calls.clear()
code, out, err = run(capsys, "ready")
assert_git_cost(git_calls, 7, 1)
assert_git_cost(git_calls, 8, 1)
assert (code, err) == (0, "") and out.endswith(f"ready: {URL}\n")
assert ["pr", "ready", "7", "--repo", REPO] in [c["argv"] for c in gh.calls]

Expand Down Expand Up @@ -3116,6 +3117,7 @@ def test_merged_bare_primary_cleans_only_clean_linked_worktree(
repo: Path, gh: FakeGh, capsys, monkeypatch, state
) -> None:
primary = repo.parent / "origin.git"
git(primary, "remote", "add", "origin", str(primary))
linked = repo.parent / "linked task"
git(primary, "worktree", "add", "-q", "-b", "lz/bare", str(linked), "main")
monkeypatch.chdir(linked)
Expand Down Expand Up @@ -3645,7 +3647,7 @@ def test_commands_refuse_base_branch(wt: Path, gh: FakeGh, capsys, base) -> None
git(wt, "checkout", "-q", "--ignore-other-worktrees", base)
else:
publish_workflow(wt, workflow.read_text())
git(wt, "update-ref", f"refs/remotes/origin/{base}", "refs/remotes/origin/main")
git(wt, "push", "-q", "origin", f"origin/main:refs/heads/{base}")
git(wt, "checkout", "-q", "-b", base)
for command in ("pr", "review", "ready", "merge"):
code, out, err = run(capsys, command)
Expand Down Expand Up @@ -4123,12 +4125,25 @@ def test_hosted_eligibility_uses_publisher_not_token(wt, gh, state, verdict, exp


@pytest.mark.parametrize("publisher", ["stranger", "lz-bot"])
def test_ready_pins_review_publishers_to_base(wt, gh, capsys, publisher, head):
(wt / "workflow.toml").write_text(WORKFLOW + f'\nreview_publishers = ["{publisher}"]\n')
def test_ready_pins_review_publishers_to_base(wt, repo, gh, capsys, monkeypatch, publisher, head):
policy = WORKFLOW.replace('required_ci = ["checks"]', 'required_ci = ["checks", "Loop-zero Eligibility"]')
publish_workflow(wt, policy + '\nreview_publishers = ["stranger"]\n')
commit_file(repo, "workflow.toml", policy + f'\nreview_publishers = ["{LOGIN}"]\n', "rotate publisher")
git(repo, "push", str(repo.parent / "origin.git"), "main") # preserve the retired local publisher
(wt / "workflow.toml").write_text(policy + f'\nreview_publishers = ["{publisher}"]\n')
arm_approved_pr_with_check_result(
gh, head, wt, "success", review_login=publisher, isDraft=False
)
gh.respond(f"api repos/{REPO}/commits/{head}/statuses", [{"context": "Loop-zero Eligibility", "state": "success"}])
assert run(capsys, "ready")[0] == (0 if publisher == LOGIN else 1)
event = repo / "event.json"
event.write_text(json.dumps({"inputs": {"pr": "7"}}))
monkeypatch.chdir(repo)
monkeypatch.setenv("GITHUB_REPOSITORY", REPO)
monkeypatch.setenv("GITHUB_EVENT_PATH", str(event))
gh.respond(f"api repos/{REPO}/statuses/{head}", {})
assert hosted.main() == 0
assert json.loads(gh.calls[-1]["--input"])["state"] == ("success" if publisher == LOGIN else "pending")


def test_mergify_confirmed_wait_reads_pr_once_per_steady_poll(wt, gh, monkeypatch):
Expand Down
Loading