Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
1960 lines (1717 loc) · 94.6 KB
/
Copy pathcli.py
File metadata and controls
1960 lines (1717 loc) · 94.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Command line: composes the modules into start, check, pr, review, ready, merge, status."""
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 json
import os
import random
import re
import shlex
import sys
import tempfile
import time
from collections.abc import Callable, Iterator
from contextlib import ExitStack, suppress
from functools import partial, wraps
from pathlib import Path
from loopzero import _proc, eligibility, github, mergify, runners, sandbox, worktree
from loopzero import config as config_mod
from loopzero.types import CheckReport, CheckResult, Config, Finding, LoopZeroError, ReviewResult, is_check_exit_code
CHECKS_FILE = Path(".loopzero") / "checks.json"
GIT_TIMEOUT = 60.0
REVIEW_MARKER_RE = eligibility.REVIEW_MARKER_RE
RUNNER_FAILURES = (runners.RunnerMissing, runners.RunnerAuthFailed, runners.RunnerBadOutput)
HANDLED = (LoopZeroError, worktree.WorktreeError, github.GhError, OSError, ValueError)
UNEXPECTED = (KeyError, TypeError)
# --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, 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
_sleep = time.sleep
OFFLINE_FAILURE_RE = re.compile(
r"failed to fetch|dns error|network is unreachable|temporary failure in name resolution|"
r"name or service not known|could not fetch url|newconnectionerror|err_pnpm_.*fetch|"
r"network request failed|max retries exceeded with url|readtimeouterror|enetunreach|"
r"econnrefused|getaddrinfo (?:enotfound|eai_again)|could not resolve host",
re.IGNORECASE,
)
class CliError(LoopZeroError):
"""A refused command; the message says what to do instead."""
class ReviewersUnavailable(CliError):
"""All reviewer failures, retained as separate diagnostic lines."""
class IndependentReviewerUnavailable(ReviewersUnavailable):
"""No independent configured model family can provide the review."""
def review_marker(head: str, kind: str, source: str = "model") -> str:
return f"<!-- loopzero:review v=1 head={head} kind={kind} source={source} -->"
# --------------------------------------------------------------------------- git / context
def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT, paths: bool = False,
extra_env: dict[str, str] | None = None) -> str:
run = _proc.run_git_paths if paths else _proc.run
done = run(["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout, extra_env=extra_env)
if done.exit_code != 0:
raise CliError(f"git {' '.join(args)} failed: {_proc.tail(done.stderr, 1)}")
return done.stdout if paths else done.stdout.strip()
def _require_push_target(wt: Path, repo: str) -> None:
urls = _git(wt, "remote", "get-url", "--push", "--all", "origin").splitlines()
github_url = re.compile(
r"(?:https://(?:[a-z0-9._~%:+-]+@)?github\.com(?::443)?/"
r"|git@github\.com:|ssh://git@github\.com(?::22)?/|ssh://git@ssh\.github\.com:443/)"
+ re.escape(repo) + r"(?:\.git)?/?",
re.IGNORECASE | re.ASCII,
)
if not urls or any(not github_url.fullmatch(url) for url in urls):
raise CliError(f"origin push URL does not target {repo}; correct the Git remote before running pr")
def _git_push(wt: Path, args: list[str], *, force_lease: bool) -> None:
done = _proc.run(["git", *args], cwd=wt, env_allowlist=worktree.GIT_ENV,
extra_env={"LC_ALL": "C"}, timeout=PUSH_TIMEOUT)
if done.exit_code != 0:
detail = _proc.tail(done.stderr)[-2000:]
if force_lease and any(line.startswith("!\t") and line.endswith("\t[rejected] (stale info)")
for line in done.stdout.splitlines()):
detail += "\nremote moved since PR lookup; fetch and retry"
raise CliError(f"git {' '.join(args)} failed: {detail.strip()}")
def _toplevel() -> Path:
return Path(_git(Path.cwd(), "rev-parse", "--show-toplevel", paths=True))
def _repo_root(wt: Path) -> None:
"""Verify the primary checkout or bare repository owns this linked worktree."""
first = _git(wt, "worktree", "list", "--porcelain", "-z", paths=True).split("\0", 1)[0]
if not first.startswith("worktree "):
raise CliError("Git did not identify the primary worktree; refusing cleanup")
root = Path(first.removeprefix("worktree "))
common = Path(_git(wt, "rev-parse", "--path-format=absolute", "--git-common-dir", paths=True)).resolve()
if root.resolve() == wt.resolve() or common not in (root.resolve(), (root / ".git").resolve()):
raise CliError("primary repository does not own this linked worktree; refusing cleanup")
def _load_config(
args: argparse.Namespace, root: Path, *, pin_checks: bool = False, previous: Config | None = None,
refresh: bool = False,
) -> Config:
require_ci = pin_checks and args.command in {"ready", "merge"} and not getattr(args, "cancel", False)
if not pin_checks or args.config:
if pin_checks:
print("checks are unpinned because --config was provided")
return config_mod.load(args.config or root / "workflow.toml", require_ci=require_ci)
config = config_mod.load_trusted(root, previous=previous, refresh=refresh,
require_ci=require_ci, read_timeout=github._read_timeout)
if args.command == "check":
if not config.checks:
raise config_mod.ConfigError(
f"origin/{config.base_branch}:workflow.toml: checks.commands must list "
"at least one command to run checks"
)
print(f"checks pinned to origin/{config.base_branch}@{config.trusted_base_revision}")
return config
def _context(args: argparse.Namespace, *, pin_checks: bool = True) -> tuple[Path, Config]:
wt = _toplevel()
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:
done = config_mod.run_git(wt, "merge-base", "--is-ancestor", sha, head)
if done.exit_code not in (0, 1):
detail = _proc.tail(done.stderr or done.stdout, 1)
raise CliError(f"git merge-base --is-ancestor failed (exit {done.exit_code}): "
f"{detail or 'retry the ancestry check'}")
return done.exit_code == 0
def _primary_base(wt: Path, config: Config) -> str:
base = config.trusted_base_revision or config_mod.base_revision(wt, config.base_branch)
done = config_mod.run_git(wt, "merge-base", base, "HEAD")
if done.exit_code == 0:
return done.stdout.strip()
if done.exit_code != 1:
raise CliError(f"git merge-base failed: {_proc.tail(done.stderr or done.stdout, 1)}")
message = f"no merge base between HEAD and the configured base {config.base_branch!r}"
if _git(wt, "rev-parse", "--is-shallow-repository") == "true":
message += ". To review, deepen or unshallow the checkout and retry"
raise CliError(message)
def _require_clean(wt: Path) -> None:
if worktree.is_dirty(wt):
raise CliError("worktree has uncommitted or untracked changes; commit or remove them first")
def _require_task_branch(config: Config, branch: str) -> None:
if branch == config.base_branch:
raise CliError(f"branch {branch!r} is the configured base; use a task branch")
def _require_pr(config: Config, branch: str, *, allow_merged: bool = False, list_only: bool = False) -> github.PR:
pr = github.pr_for_branch(config.repo, branch, list_only=list_only)
if pr is None:
raise CliError(f"no pull request for {branch}; run `loopzero pr` first")
if pr.state != "OPEN" and not (allow_merged and pr.state == "MERGED"):
raise CliError(f"PR #{pr.number} is {pr.state}, not open: {pr.url}")
return pr
def _require_pushed(pr: github.PR, head: str) -> None:
if pr.head_sha != head:
raise CliError(
f"PR head {pr.head_sha[:12]} differs from local {head[:12]}; push or pull first"
)
# --------------------------------------------------------------------------- review markers
def _rest_rows(endpoint: str, what: str, **kwargs) -> list[dict]:
"""Every row of a REST list, oldest first, following pages until a short one."""
rows: list[dict] = []
for page in range(1, 101):
batch = github.api_get(f"{endpoint}?per_page={github.PAGE}&page={page}", **kwargs)
if not isinstance(batch, list) or not all(isinstance(row, dict) for row in batch):
raise CliError(f"invalid GitHub {what} response")
rows += batch
if len(batch) < github.PAGE:
return rows
raise CliError(f"GitHub {what} pagination limit exceeded")
def _pr_reviews(repo: str, number: int, **kwargs) -> list[dict]:
return _rest_rows(f"repos/{repo}/pulls/{number}/reviews", "reviews", **kwargs)
@dataclasses.dataclass(frozen=True)
class Marker:
head: str
kind: str
state: str
def _pr_markers(reviews: list[dict], head: str,
publishers: tuple[str, ...] = (), *, repo: str = "", number: int = 0) -> list[Marker]:
"""Trusted publisher markers on their named commits across the PR."""
found: list[Marker] = []
trusted = {login.casefold() for login in publishers}
for review in reviews:
body = review.get("body") or ""
if not eligibility.review_projection(review, head, repo, number)[0] and any(
runners.codex_fatal_startup(item) for item in eligibility.review_envelopes(body)[1]):
continue
match = eligibility.leading_marker(body)
if not match or review.get("commit_id") != match.group(1):
continue
if not trusted:
trusted = {github.login().casefold()}
if (review.get("user") or {}).get("login", "").casefold() not in trusted:
continue
found.append(Marker(match.group(1), match.group(2), review.get("state") or ""))
return found
def _review_cap_spent(markers: list[Marker]) -> bool:
return len({m.head for m in markers}) >= 2 or {m.kind for m in markers} >= {"primary", "delta"}
def _decide_kind(markers: list[Marker], head: str) -> tuple[str, str | None]:
"""Return (kind, reviewed_head) or raise when the PR's review budget is spent."""
if _review_cap_spent(markers):
raise CliError(
"review cap reached: fix or reject the findings "
"(resolve-findings) and run `loopzero ready`, or split the PR"
)
primary = next((m for m in markers if m.kind == "primary"), None)
if primary is None:
return "primary", None
reviewed = primary.head
if head.startswith(reviewed) or reviewed.startswith(head):
raise CliError(f"head {head[:12]} already has a primary review; run `loopzero ready`, or push fixes for the delta")
return "delta", reviewed
def _conflict_delta_base(config: Config, pr: github.PR, head: str, reviews: list[dict],
markers: list[Marker], publishers: tuple[str, ...]) -> str | None:
rounds = list(dict.fromkeys((marker.kind, marker.head) for marker in markers))
if [kind for kind, _ in rounds] != ["primary", "delta"]:
return None
(_, primary), (_, reviewed) = rounds
if len({primary, reviewed, head}) != 3:
return None
publishers = publishers or (github.login(),)
if (not eligibility.approved_delta(reviews, reviewed, publishers, repo=config.repo, number=pr.number)
or eligibility.base_merge_material(
config.repo, pr.number, reviewed, head, config.base_branch, clean=False, conflict_only=True,
) is None or github.open_blocking_findings(config.repo, pr.number, None, publishers)):
return None
return reviewed
def _select_review_round(config: Config, pr: github.PR, head: str, reviews: list[dict]) -> tuple[str, str | None]:
publishers = config.review_publishers
markers = _pr_markers(reviews, head, publishers, repo=config.repo, number=pr.number)
if reviewed := _conflict_delta_base(config, pr, head, reviews, markers, publishers):
return "delta", reviewed
return _decide_kind(markers, head)
MERGEABILITY_PENDING = github.MERGEABILITY_PENDING
def _readiness(
wt: Path, config: Config, pr: github.PR, head: str, reviews: list[dict] | None = None,
*, workflow_wait: bool = False, announce_receipt: bool = False, diagnostics: bool = False,
mergify_deadline: float | None = None,
) -> github.Readiness:
if problem := github.merge_hold(pr.number, pr.labels) or (
None if diagnostics else _check_report_problem(_load_report(wt), config, head)
):
return github.Readiness(False, (problem,))
dates: list[str] = []
reviews = (_pr_reviews(config.repo, pr.number, **({"dates": dates} if workflow_wait else {}))
if reviews is None else reviews)
publishers = config.review_publishers or (github.login(),)
review = eligibility.readiness_review(
reviews, head, publishers, repo=config.repo, number=pr.number, base_branch=config.base_branch,
)
review_at = github.readiness_timestamp(review.get("submitted_at")) if review else None
server = github.response_date(dates[-1]) if dates else None
now = server.timestamp() if server else time.time()
review_age = now - review_at[0].timestamp() if review_at else None
if server and review_age is not None and -1 < review_age < 0:
review_age = 0 # HTTP Date rounds down to the second.
result = github.readiness(
config.repo, pr, config.base_branch, config.required_ci,
head if review else None, review_at=review_at,
ancestor_review=review is not None and review["commit_id"] != head,
review_grace=review_age is not None and 0 <= review_age < MISSING_RUN_GRACE,
workflow_wait=workflow_wait,
# Allow host clock skew only when GitHub did not supply a usable Date.
stale_verdict_grace=(
workflow_wait and review_age is not None
and (0 if server else -MAX_REVIEW_CLOCK_SKEW) <= review_age < STALE_VERDICT_GRACE
),
publishers=publishers,
)
if config.merge_strategy == "mergify" and pr.state == "OPEN":
behind = github.behind_reason(pr, head if review else None)
reasons = result.reasons
if mergify.configured(config.repo, config.base_branch, config.mergify_queue or "", mergify_deadline):
reasons = tuple(reason for reason in reasons if reason != behind)
else:
reasons = (*reasons, "Mergify queue configuration is unverified or permits in-place head updates")
result = dataclasses.replace(result, ready=not reasons, reasons=reasons)
if github.MISSING_REVIEW_REASON in result.reasons:
markers = _pr_markers(reviews, head, publishers, repo=config.repo, number=pr.number)
if _review_cap_spent(markers) and all(marker.head != head for marker in markers):
if _conflict_delta_base(config, pr, head, reviews, markers, publishers):
exhausted = f"Run `loopzero review` for the available conflict-resolution delta on {head[:12]}."
else:
exhausted = (
f"The review budget is exhausted and {head[:12]} has no eligible review. "
"Open a replacement PR for changes that need review. Another `loopzero review` on this PR will be refused."
)
result = dataclasses.replace(result, reasons=tuple(
exhausted if reason == github.MISSING_REVIEW_REASON else reason for reason in result.reasons
))
report = _load_report(wt)
receipt_problem = _check_report_problem(report, config, head)
if receipt_problem:
return github.Readiness(False, (*result.reasons, receipt_problem))
if announce_receipt:
_print_receipt(wt, report, "accepted")
return result
# --------------------------------------------------------------------------- checks report
def _check_report_problem(
report: CheckReport | None, config: Config, head: str, *, require_pass: bool = True,
) -> str | None:
if report is None:
return "run loopzero check at this head"
if report.head != head:
return f"check receipt is for {report.head[:12]}. Run `loopzero check` at {head[:12]}."
if report.dirty:
return ("check receipt was recorded in a dirty worktree. Run `git status --short`, "
"settle the changes, then run `loopzero check`.")
commands = tuple(result.command for result in report.results)
if (require_pass and not report.ok) or commands != config.checks:
if not commands or commands[-1] == sandbox.INCOMPLETE_CHECK_COMMAND:
return "check receipt is incomplete. Run `loopzero check` to resume with the current workflow."
if require_pass and not report.ok:
return ("check receipt records a failed stage. Fix the failure, then run `loopzero check`. "
"Retry unchanged only if the failure was transient.")
return ("check receipt's plan differs from the trusted workflow. "
"Run `loopzero check` with the current workflow.")
recovery = ("Run loopzero check in this worktree at this head with the same current CLI and effective "
"settings as ready, using a local coordinator for delegated stages.")
if report.settings_sha256 is None:
return f"check receipt is missing its settings fingerprint. {recovery}"
if report.settings_sha256 != sandbox.settings_fingerprint(config):
return f"check receipt has an incompatible settings fingerprint. {recovery}"
return None
def _current_check_report(wt: Path, config: Config, head: str) -> CheckReport | None:
report = _load_report(wt)
return None if _check_report_problem(report, config, head) else report
def _require_receipt(wt: Path, config: Config, head: str) -> None:
if problem := _check_report_problem(_load_report(wt), config, head):
raise CliError(problem)
def _print_receipt(wt: Path, report: CheckReport, action: str) -> None:
"""Best-effort transcript identity; never authority or environment attestation."""
with suppress(Exception):
content = _git(wt, "rev-parse", f"{report.head}^{{tree}}").strip()
commands = json.dumps([r.command for r in report.results], separators=(",", ":"))
digest = hashlib.sha256(commands.encode()).hexdigest()
print(f"receipt {action}: head={report.head} content={content} "
f"config=commands-sha256:{digest} environment=unknown")
def _save_report(
wt: Path, report: CheckReport, *, checkpoint_checks: tuple[str, ...] | None = None, locked_fd: int | None = None,
) -> str | None:
"""Publish the receipt or return the current HEAD if the result is stale."""
results = [
{k: v for k, v in dataclasses.asdict(result).items()
if k not in {"input_key", "reused_from"} or v is not None}
for result in report.results
]
payload = {"head": report.head, "dirty": report.dirty, "results": results}
if report.settings_sha256 is not None:
payload["settings_sha256"] = report.settings_sha256
def preserve_checkpoint() -> bool:
if report.results[-1] is not sandbox.INCOMPLETE_CHECK:
return not worktree.local_state_files(wt, CHECKS_FILE.name)[0]
saved = _load_report(wt)
return (saved is not None and saved.ok and not saved.dirty and saved.head == report.head
and saved.settings_sha256 == report.settings_sha256
and tuple(result.command for result in saved.results) == checkpoint_checks)
return worktree.write_local_state(
wt, CHECKS_FILE.name, json.dumps(payload, indent=2) + "\n", expected_head=report.head, locked_fd=locked_fd,
preserve=preserve_checkpoint if checkpoint_checks is not None else None,
)
def _load_report(wt: Path) -> CheckReport | None:
path = wt / CHECKS_FILE
try:
data = json.loads(worktree.read_local_state(wt, path.name))
results = tuple(CheckResult(**item) for item in data["results"])
if any(not is_check_exit_code(result.exit_code) for result in results):
raise TypeError("exit_code must be an integer")
dirty = data.get("dirty", True)
if not isinstance(dirty, bool):
raise TypeError("dirty must be a bool")
return CheckReport(head=str(data["head"]), dirty=dirty, results=results,
settings_sha256=data.get("settings_sha256"))
except FileNotFoundError:
return None
except (TypeError, KeyError, ValueError) as exc:
print(f"warning: ignoring unreadable {path}: {exc}", file=sys.stderr)
return None
def _validation_section(wt: Path, head: str, config: Config) -> str:
loaded = _load_report(wt)
if loaded is None:
return "(no `loopzero check` run recorded)"
heading = f"Recorded for `{loaded.head[:12]}`" + ("" if loaded.head == head else " (not current head)")
if _check_report_problem(loaded, config, head, require_pass=False):
heading += " (unverified, run `loopzero check`)"
results = [f"- `{github.redact_credentials(r.command)}`: exit {r.exit_code}" for r in loaded.results]
return "\n".join([heading, *(results or ["- (no check commands configured)"])])
_CHECKS_START = "<!-- loopzero:checks:start -->"
_CHECKS_END = "<!-- loopzero:checks:end -->"
_LEGACY_CHECKS = re.compile(
r"^Recorded for `[0-9a-f]+`(?: \(not current head\))?\n"
r"(?:- `[^\n]+`: exit -?\d+ \(\d+\.\d+s\)\n|"
r"- \(no check commands configured\)\n)*",
re.MULTILINE,
)
def _pr_body(wt: Path, head: str, config: Config, existing: str | None = None) -> str:
"""Refresh only generated checks; the live body owns existing PR prose."""
body = (existing if existing is not None else worktree.task_text(wt)).replace("\r\n", "\n")
block = f"{_CHECKS_START}\n{_validation_section(wt, head, config)}\n{_CHECKS_END}"
match = re.search(r"^## (?:Validation|Checks)\n(.*?)(?=^## |\Z)", body, re.DOTALL | re.MULTILINE)
if match is None:
return _validate_pr_body_size(f"{body.rstrip()}\n\n## Validation\n{block}\n")
content = match.group(1)
before, start, after = content.partition(_CHECKS_START)
if start or _CHECKS_END in content:
_, end, suffix = after.partition(_CHECKS_END)
if not end or _CHECKS_END in before or _CHECKS_END in suffix or _CHECKS_START in after:
raise CliError("malformed loopzero checks block in PR Validation; repair its markers")
content = before + block + suffix
else:
# Migrate our old report/placeholder only, retaining behavioral evidence.
content = _LEGACY_CHECKS.sub("", content)
content = re.sub(
r"^\((?:filled by `loopzero check`|no `loopzero check` run recorded)\)\n?",
"", content, flags=re.MULTILINE,
)
content = block + "\n" + ("\n" + content.lstrip("\n") if content.strip() else "\n")
return _validate_pr_body_size(body[:match.start()] + "## Validation\n" + content + body[match.end():])
def _validate_pr_body_size(body: str) -> str:
limit = 65_536
if len(body) > limit:
raise CliError(
f"generated PR body is {len(body)} characters; GitHub allows {limit}. "
"Shorten the PR description or validation text and rerun the command."
)
return body
def _sync_task_narrative(wt: Path, existing: str) -> str:
"""Explicit pr updates task-owned sections; live evidence/reviews stay authoritative."""
pattern = re.compile(r"^## ([^\n]+)\n.*?(?=^## |\Z)", re.MULTILINE | re.DOTALL)
task = worktree.task_text(wt).replace("\r\n", "\n")
existing = existing.replace("\r\n", "\n")
owned = {m.group(1): m.group() for m in pattern.finditer(task)
if m.group(1) not in {"Validation", "Checks", "Review"}}
content = existing[first.start():] if (first := pattern.search(existing)) else ""
prefix = task[:first.start()] if (first := pattern.search(task)) else task
def replace(match: re.Match[str]) -> str:
section = match.group()
replacement = owned.pop(match.group(1), section)
trailing = section[len(section.rstrip()):]
return replacement.rstrip() + trailing
content = pattern.sub(replace, content)
for section in owned.values():
content = content.rstrip() + "\n\n" + section
return prefix + content.lstrip("\n")
_REQUIRED_TASK_LINES = ("Context", "Problem", "Goal")
def _require_pr_details(wt: Path) -> None:
"""Report every unfilled PR description field before push."""
task = worktree.task_text(wt)
unfilled = []
for name in _REQUIRED_TASK_LINES:
match = re.search(rf"^- \*\*{name}:\*\*[ \t]*(.*(?:\n[ \t]+\S.*)*)", task, re.MULTILINE)
value = match.group(1).strip() if match else ""
if not value or re.fullmatch(r"<[^<>]*>", value):
unfilled.append(f"'- **{name}:**'")
if unfilled:
raise CliError(
f"fill {', '.join(unfilled)} in {worktree.task_file(wt)}"
" (Context, Problem and Goal become the PR description)"
)
def _append_review(body: str, result: ReviewResult) -> str:
"""Append one compact review record under Review, replacing its placeholder."""
line = f"- {result.kind}, {result.family}, {result.head[:12]}, {result.verdict}"
match = re.search(r"^## Review\n(.*?)(?=^## |\Z)", body, re.DOTALL | re.MULTILINE)
if not match:
return f"{body.rstrip()}\n\n## Review\n{line}\n"
existing = match[1].rstrip()
if existing and not existing.startswith("(filled by `loopzero review`)"):
line = f"{existing}\n{line}"
return (body[:match.start(1)] + line + "\n\n" + body[match.end():]).rstrip() + "\n"
def _refresh_pr_checks(wt: Path, config: Config) -> None:
"""Best-effort refresh only when local HEAD is the existing PR head."""
try:
upstream = config_mod.run_git(wt, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}")
if upstream.exit_code != 0:
return
branch, head = worktree.branch(wt), worktree.head(wt)
pr = github.pr_for_branch(config.repo, branch, open_only=True)
if pr is None or pr.head_sha != head:
return
with github.pr_lock(config.repo, pr.number):
live = github.pr_view(config.repo, pr.number)
if live.state != "OPEN" or live.head_sha != head:
return
body = _pr_body(wt, head, config, live.body)
if body != live.body.replace("\r\n", "\n"):
github.update_body(config.repo, pr.number, body)
except (github.GhError, _proc.ProcTimeout, OSError, ValueError, CliError, worktree.WorktreeError) as exc:
print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr)
_SECTIONS = {
"objective", "context and goal", "acceptance", "base", "checks", "validation",
"review", "notes",
}
def _pr_title(wt: Path, branch: str) -> str:
"""First heading of task.md that is not a template section name; else the branch."""
headings = [ln.lstrip("#").strip() for ln in worktree.task_text(wt).splitlines() if ln[:1] == "#"]
return next((t for t in headings if t and t.lower() not in _SECTIONS), branch)
def cmd_start(args: argparse.Namespace) -> int:
root = _toplevel()
current = config_mod.run_git(root, "symbolic-ref", "--quiet", "--short", "HEAD")
if current.stdout.strip().startswith("lz/") or (
current.exit_code == 1 and worktree.is_linked_checkout(root)
):
raise CliError(f"already inside task worktree {root}; run start from the main checkout")
config = _load_config(args, root)
print(worktree.start(root, args.slug, config.base_branch))
return 0
def _check_failure_preview(tail: str, limit: int = 1536) -> str:
if len(tail.encode()) <= limit:
return tail
edge = limit // 8
lines = (line.encode() for line in tail.splitlines())
preview = b"\n".join(
line if len(line) <= 2 * edge else line[:edge] + b" [...] " + line[-edge:]
for line in lines
)
if len(preview) > limit:
preview = b"[...]\n" + preview[6 - limit:]
return preview.decode(errors="ignore")
def cmd_check(args: argparse.Namespace) -> int:
wt, config = _context(args)
worktree.local_state_files(wt, CHECKS_FILE.name)
if not config.checks:
raise config_mod.ConfigError("checks.commands must list at least one command to run checks")
before = _receipt_inode(wt / CHECKS_FILE)
with worktree.lock_local_state(wt) as fd:
if (_receipt_inode(wt / CHECKS_FILE) != before
and (report := _current_check_report(wt, config, worktree.head(wt))) is not None
and not worktree.is_dirty(wt) and sandbox.check_inputs_match(config, wt, report)):
_print_receipt(wt, report, "reused")
print("PASS")
return 0
report = sandbox.run_checks(
config, wt, progress=lambda command: print(f"running: {github.redact_credentials(command)}", flush=True),
status=lambda message: print(message, flush=True),
checkpoint=partial(_save_report, wt, checkpoint_checks=config.checks, locked_fd=fd),
workflow=args.config or f"origin/{config.base_branch}:workflow.toml",
)
return _finish_check(wt, config, report, fd)
def _receipt_inode(path: Path) -> int | None:
try:
return path.lstat().st_ino
except FileNotFoundError:
return None
def _finish_check(wt: Path, config: Config, report: CheckReport, locked_fd: int) -> int:
shortened = False
for result in report.results:
if result.exit_code != 0:
heading = github.redact_credentials(result.command)
print(f"--- {heading} (exit {result.exit_code}) ---", file=sys.stderr)
tail = _proc.tail(result.tail)
preview = _check_failure_preview(tail)
shortened |= preview != tail
print(preview, file=sys.stderr)
if not config.network and (result.command.startswith("uv sync --offline --locked")
or OFFLINE_FAILURE_RE.search(tail)):
env = sandbox.check_environment(config)
print(
"\nThe sandbox has no network because `[checks] network = false`; "
f"the effective UV_CACHE_DIR inside the sandbox is {env['UV_CACHE_DIR']}. "
"Run UV_CACHE_DIR=<effective-cache> uv sync --group dev on the host "
"(use the required groups) so the cache under `[checks] writable` is warm, "
"or set `[checks] env` UV_CACHE_DIR to a warm cache.", file=sys.stderr,
)
if (current_head := _save_report(wt, report, locked_fd=locked_fd)) is not None:
print(f"check result discarded: checked HEAD {report.head}, current HEAD {current_head}",
file=sys.stderr)
return 1
fcntl.flock(locked_fd, fcntl.LOCK_UN)
if shortened:
print(f"Full diagnostic tail: {CHECKS_FILE} (head {report.head})", file=sys.stderr)
verified = not report.ok or report.settings_sha256 is not None
if not verified:
print("check stages passed but the receipt is unverified; rerun loopzero check from the task "
"worktree with a stable, readable configured runner before running ready", file=sys.stderr)
elif report.ok and not report.dirty:
_print_receipt(wt, report, "produced")
_refresh_pr_checks(wt, config)
if verified:
print("PASS" if report.ok else "FAIL")
return 0 if report.ok and verified else 1
def cmd_pr(args: argparse.Namespace) -> int:
wt, config = _context(args)
branch, head = worktree.branch(wt), worktree.head(wt)
_require_task_branch(config, branch)
_require_clean(wt)
_require_pr_details(wt)
pr = github.merged_pr_for_branch(config.repo, branch)
if pr is not None:
raise CliError(
f"task branch {branch} already merged as PR #{pr.number} ({pr.url}); "
"run `loopzero start <new-task-slug>` for a new task"
)
pr = github.pr_for_branch(config.repo, branch, open_only=True)
existing = _sync_task_narrative(wt, pr.body or "") if pr is not None else None
body = _pr_body(wt, head, config, existing)
force_lease = False
git_branch = os.fsdecode(branch.encode("utf-8", "surrogateescape"))
push = ["push", "-u", "origin"]
if pr is not None:
known = config_mod.run_git(wt, "cat-file", "-e", f"{pr.head_sha}^{{commit}}")
if known.exit_code != 0:
raise CliError(
f"PR head {pr.head_sha[:12]} is not in this worktree; fetch and integrate it first"
)
force_lease = pr.head_sha != head and not _is_ancestor(wt, pr.head_sha, head)
if force_lease:
previous_heads = _git(wt, "reflog", "show", "--format=%H", f"refs/heads/{git_branch}").splitlines()
if not any(_is_ancestor(wt, pr.head_sha, previous) for previous in previous_heads):
raise CliError(
f"PR head {pr.head_sha[:12]} is absent from this task branch's history; integrate it first"
)
push.extend(("--porcelain", f"--force-with-lease={git_branch}:{pr.head_sha}"))
push.append(git_branch)
_require_push_target(wt, config.repo)
_git_push(wt, push, force_lease=force_lease)
if pr is not None:
with github.pr_lock(config.repo, pr.number):
live = github.pr_view(config.repo, pr.number)
if live.state != "OPEN":
raise CliError(f"PR #{pr.number} closed during publication")
body = _pr_body(wt, head, config, _sync_task_narrative(wt, live.body or ""))
if body != live.body.replace("\r\n", "\n"):
github.update_body(config.repo, pr.number, body)
else:
pr = github.create_draft_pr(
config.repo, branch, config.base_branch, _pr_title(wt, branch), body
)
print(pr.url)
return 0
# Published fallback reasons; --repost posts a saved note only in the form a fresh run would publish.
_FALLBACK_REASONS = ("not authenticated", "usage limit", "not installed", "unavailable")
def _published_fallback(note: str, candidates: list[str], excluded: list[str]) -> bool:
if not candidates:
return note == "every configured family contributed (" + ", ".join(excluded) + ")"
prefix = "independent reviewers failed: "
if not note.startswith(prefix):
return False
parts = [part.partition(": ") for part in note[len(prefix):].split("; ")]
return ([family for family, _sep, _reason in parts] == candidates
and all(reason in _FALLBACK_REASONS for _family, _sep, reason in parts))
def _require_review_pr(config: Config, branch: str, *, repost: bool) -> github.PR:
try:
return _require_pr(config, branch)
except github.GhError as exc:
if "HTTP 404" not in exc.tail or exc.command[:2] != ("gh", "api"):
raise
endpoint = exc.command[2]
pulls = f"repos/{config.repo}/pulls"
retry = "loopzero review --repost" if repost else "loopzero review"
number = endpoint.removeprefix(f"{pulls}/")
if endpoint.startswith(f"{pulls}/") and number.isdecimal():
raise CliError(
f"Could not read PR #{number}. Verify that PR and its branch {branch!r}, "
f"then rerun `{retry}`. {exc}"
) from exc
if exc.tail.endswith(github.PR_APP_INSTALLATION_HINT):
raise CliError(f"{exc}\nThen rerun `{retry}`.") from exc
raise
def _lock_review(run_review: Callable[[argparse.Namespace, Path, Config], int]):
@wraps(run_review)
def locked(args: argparse.Namespace) -> int:
wt, config = _context(args)
git_dir = _git(wt, "rev-parse", "--absolute-git-dir", paths=True)
with ExitStack() as cleanup:
fd = os.open(git_dir, os.O_RDONLY | os.O_DIRECTORY)
cleanup.callback(os.close, fd)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError as exc:
raise CliError("review already running in this worktree") from exc
return run_review(args, wt, config)
return locked
@_lock_review
def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
runtime_source = (
"reviewer paths are unpinned because --config was provided" if args.config
else f"reviewer paths pinned to origin/{config.base_branch}@{config.trusted_base_revision}"
)
branch, head = worktree.branch(wt), worktree.head(wt)
_require_task_branch(config, branch)
kinds = ("primary", "delta")
_, *saved_files = worktree.local_state_files(
wt, "task.md", *(_review_file(wt, head, kind).name for kind in kinds)
)
_require_clean(wt)
pr = _require_review_pr(config, branch, repost=args.repost)
_require_pushed(pr, head)
if pr.base_ref != config.base_branch:
raise CliError(f"PR targets {pr.base_ref}, configured base is {config.base_branch}")
token = github.app_token() # one identity for the publisher check and the post
publisher = github.login(token=token)
if config.review_publishers and publisher.casefold() not in {
login.casefold() for login in config.review_publishers
}:
raise CliError("current GitHub login is not a configured review publisher")
saved = [kind for kind, exists in zip(kinds, saved_files, strict=True) if exists] if args.repost else []
if len(saved) > 1:
raise CliError("multiple saved reviews for HEAD; publication is ambiguous")
reviews = [] if saved else _pr_reviews(config.repo, pr.number)
kind, reviewed = (saved[0], None) if saved else _select_review_round(config, pr, head, reviews)
publication_context = {"repo": config.repo, "number": pr.number, "publisher": publisher}
if args.repost:
result, publication = _load_review(wt, head, kind)
candidates, excluded = _repost_reviewer_families(wt, config, head, result)
if publication is not None:
if (not isinstance(publication, dict) or publication.get("repo") != config.repo
or publication.get("number") != pr.number
or not isinstance(publication.get("publisher"), str)
or not publication["publisher"]):
raise CliError("saved publication identity differs from this repository/PR")
confirmed, reviews = _recover_review(wt, config, pr, result,
publication["publisher"], token)
if confirmed:
return _review_verdict(result)
else:
reviews = _pr_reviews(config.repo, pr.number)
# Exact read-back above may confirm an older published note; a new post needs the current form.
if result.fallback and not _published_fallback(result.fallback, candidates, excluded):
raise CliError("saved fallback note is not in the published form; run without --repost")
allowed, reviewed = _select_review_round(config, pr, head, reviews)
if allowed != kind:
raise CliError("saved review kind differs from the remaining review budget")
_delta_patch(wt, config, reviewed, head, pr.number)
else:
if args.model is None and args.effort is None and _has_recoverable_review(
wt, config, head, kind, publication_context,
):
raise CliError(f"saved {kind} review for {head[:12]}; run `loopzero review --repost`")
result = _run_review(wt, config, head, kind, reviewed, args.model, args.effort,
runtime_source=runtime_source, publication=(config.repo, pr.number, publisher))
final_head, final_dirty = worktree.head(wt), worktree.is_dirty(wt)
if final_head != head or final_dirty:
raise CliError(
f"worktree changed during review: HEAD before {head}, HEAD after {final_head}; "
f"dirty before False, dirty after {final_dirty}"
)
try:
if not _matches_publication(result, publication_context):
raise CliError("native publication context changed; HOLD")
except runners.RunnerBadOutput:
_save_review(wt, result)
raise
prefix = _repost_prefix(result) if args.repost else review_marker(head, kind, "model")
_save_review(wt, result, publication_context)
token = _refresh_publisher_token(token, publisher)
with github.pr_lock(config.repo, pr.number):
_require_open_review_round(config, pr, head, kind)
try:
github.post_review(
config.repo, pr.number, head, result, body_prefix=prefix, pr=pr, token=token,
publisher=publisher,
)
except (github.GhError, _proc.ProcTimeout) as exc:
path = _review_file(wt, head, kind)
try:
if _recover_review(wt, config, pr, result, publisher, token)[0]:
return _review_verdict(result)
except (github.GhError, CliError, _proc.ProcTimeout) as recovery:
raise CliError(f"{exc} | publication read-back blocked: {recovery}; "
f"review saved at {path}; retry `loopzero review --repost` "
"after resolving the read-back failure") from recovery
raise CliError(
f"{exc} | publication unconfirmed; review saved at {path}; "
"inspect the cause and run `loopzero review --repost` to reconcile or explicitly retry"
) from exc
try:
live = github.pr_view(config.repo, pr.number)
github.update_body(config.repo, pr.number, _append_review(live.body, result))
except (github.GhError, _proc.ProcTimeout, OSError, ValueError) as exc:
print(f"note: could not append PR review summary: {_one_line(exc)}", file=sys.stderr)
return _review_verdict(result)
def _require_open_review_round(config: Config, pr: github.PR, head: str, kind: str) -> None:
reviews = _pr_reviews(config.repo, pr.number)
markers = _pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number)
if any(marker.kind == kind and marker.head == head for marker in markers):
raise CliError(f"the {kind} review round is already taken; run loopzero ready")
if _select_review_round(config, pr, head, reviews)[0] != kind:
raise CliError("review round changed during publication; run loopzero review again")
def _refresh_publisher_token(token: str, publisher: str) -> str:
"""The review may outlive the app token: re-mint it, but only for the same publisher."""
if not token or (fresh := github.app_token()) == token:
return token
if not fresh or github.login(token=fresh).casefold() != publisher.casefold():
raise CliError(f"could not refresh the app token for review publisher {publisher}; the review "
"is saved: fix the app token helper, then run `loopzero review --repost`")
return fresh
def _review_verdict(result: ReviewResult) -> int:
summary = ", ".join(f"{sum(f.severity == s for f in result.findings)} {s}" for s in runners.SEVERITIES)
print(f"{result.kind} review by {result.family} on {result.head[:12]}: {result.verdict} ({summary})")
return 0 if result.verdict == "approve" else 5 # the exit code is the verdict, as for check
def _repost_reviewer_families(
wt: Path, config: Config, head: str, result: ReviewResult,
) -> tuple[list[str], list[str]]:
authors = runners.author_families(wt, head, _primary_base(wt, config))
candidates = [family for family in config.reviewers if family not in authors]
excluded = [family for family in config.reviewers if family in authors]
if result.fallback and result.family not in excluded:
raise CliError(
f"saved review claims a same-family fallback, but {result.family} is not a configured "
"reviewer family that contributed to this PR lineage; run without --repost"
)
if not result.fallback and not candidates:
raise IndependentReviewerUnavailable(_independence_message(authors, excluded, []))
if result.family in authors and not result.fallback:
raise IndependentReviewerUnavailable(
f"saved reviewer family {result.family} contributed to this PR lineage; "
"run without --repost to obtain an independent review"
)
return candidates, excluded
def _matches_publication(result: ReviewResult, publication: dict) -> bool:
evidence = runners.codex_evidence(result)
return evidence is None or (evidence["repo"], evidence["pr"], evidence["publisher"]) == (
publication["repo"], publication["number"], publication["publisher"]
)
def _has_recoverable_review(
wt: Path, config: Config, head: str, kind: str, publication: dict,
) -> bool:
other_kind = "delta" if kind == "primary" else "primary"
if not _review_file(wt, head, kind).exists() or _review_file(wt, head, other_kind).exists():
return False
try:
result, _ = _load_review(wt, head, kind, publication=publication)
candidates, excluded = _repost_reviewer_families(wt, config, head, result)
fallback_valid = not result.fallback or _published_fallback(result.fallback, candidates, excluded)
return fallback_valid and _matches_publication(result, publication)
except (CliError, runners.RunnerBadOutput):
return False
def _repost_prefix(result: ReviewResult) -> str:
sessions = result.provenance["session_ids"]
label = "session" if len(sessions) == 1 else "sessions"
ids = ", ".join(f"`{session}`" for session in sessions)
return f"{review_marker(result.head, result.kind, 'repost')}\nReposted from runner {label}: {ids}"
def _recover_review(wt: Path, config: Config, pr: github.PR, result: ReviewResult,
publisher: str, token: str) -> tuple[bool, list[dict]]:
with github.bounded_reads(time.monotonic() + 30, token=token, retry=True):
reviews = _pr_reviews(config.repo, pr.number)
return _confirm_review(wt, config, pr, result, publisher, reviews), reviews
def _review_formats(result: ReviewResult) -> list[tuple[str, github.ReviewSettingsLayout, bool]]:
old_settings = "requested_settings" not in result.provenance
formats: list[tuple[github.ReviewSettingsLayout, bool]] = [("current", False)]
codex = runners.codex_evidence(result)
if codex is None:
formats.append(("current", True))
if old_settings:
formats.append(("summary", True))
if result.family == "claude" and not old_settings and "configured_settings" not in result.provenance:
formats.append(("requested-reported", True))
if codex is not None and all("configured" not in call for call in codex["calls"]):
formats.append(("requested-reported", False))
if result.family == "codex" and old_settings:
formats.append(("summary", False))
return [(prefix, settings, display)
for prefix in (review_marker(result.head, result.kind, "model"), _repost_prefix(result))
for settings, display in formats]
def _confirm_review(wt: Path, config: Config, pr: github.PR, result: ReviewResult,
publisher: str, reviews: list[dict]) -> bool:
"""Confirm an exact live publication; absence authorizes no automatic write."""
trusted = config.review_publishers or (publisher,)
evidence = [r for r in reviews if "loopzero:review" in (r.get("body") or "") and (
r.get("commit_id") == result.head
or ((marker := eligibility.leading_marker(r["body"])) and marker.group(1) == result.head))]
fresh = github.pr_view(config.repo, pr.number)
if fresh.head_sha != result.head or fresh.state != "OPEN" or fresh.base_ref != pr.base_ref: