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
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,8 @@ ownership and the contributor routine that keeps documentation current.

For a picture of the whole flow, see the [workflow diagrams](docs/WORKFLOW.md).

`loopzero status` prints where the current branch is in that sequence. It
requires authenticated access to the configured GitHub repository even before
a PR exists.
`loopzero status` reports the branch stage and can exit 0 with `ready: no`.
It requires authenticated GitHub access even before a PR exists.
`loopzero resolve` lists the open blocking findings with their ids;
`loopzero resolve <id> "<what changed>"` replies in that thread and resolves it.

Expand Down
8 changes: 4 additions & 4 deletions core/CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,9 @@ version.

- Findings live only in PR review threads, expire at merge, and must not be
copied into files, issues or backlogs.
- Blocking marker:
- Blocking marker, as the first line of a thread a review publisher opened:
`<!-- loopzero:finding v=1 severity=critical head=<sha> id=<8-hex> -->`
(or `important`).
(or `important`). Other threads never block.
- `critical`: wrong or unsafe; must fix. `important`: ships a bug or breaks
acceptance; must fix. `suggestion`: never counted or blocking.
- Missing diff or required evidence: return one `critical` finding; never
Expand Down Expand Up @@ -285,8 +285,8 @@ meta-directives; reviewers load no instruction files or skills from the reviewed
Fail closed on missing tools and command errors, preserve the failing command
and output tail, and keep a short, safe detail about the cause or stage when
operator-facing code wraps an error. Stop on terminal failures or quota errors.
Exit 3 means waiting: rerun the bounded waiter. Exit 5 means changes requested,
not a crash.
Exit 3 means waiting or timeout. Review exits 4 when independent review is
unavailable and 5 when changes are requested. Interruption exits 130.

**Never pipe a `loopzero` command, even with `set -o pipefail`: the pipeline
can report the filter's exit code in place of the command's verdict.** Redirect
Expand Down
5 changes: 3 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ loading the delivery [commands](../src/loopzero/cli.py), which implement the con
[owner-approved contributor-review exception](../core/CONTRACT.md#owner-approved-contributor-review-exception),
which changes neither the selector nor the budget.
5. `ready` derives readiness from the current head, its check receipt, an eligible review at that
head or an eligible review covering an ancestor, blocking findings,
head or an eligible review covering an ancestor, blocking findings
(unresolved threads a review publisher opened with a head-bound marker line),
target branch and required CI. The receipt must record a clean passing run
at that head with the current commands and check settings digest. A settings
change or an older receipt without the digest requires a fresh check. The
Expand Down Expand Up @@ -281,7 +282,7 @@ Git configuration so URL rewrites cannot change its destination.
After confirmed remote deletion or absence, cleanup deletes the matching
`origin/lz/<slug>` tracking ref only if it still points to the merged head.
An already-merged PR can resume cleanup from its task worktree. Local removal
requires a clean worktree at the merged PR head.
requires a clean worktree at the merged PR head with no ignored user files.
Hosted eligibility trusts the configured publisher's projection and live identity,
state, head and latest ordering. It cannot recompute private raw or defeat a
coherent forgery by a trusted publisher/editor; native claims do not attest the
Expand Down
12 changes: 8 additions & 4 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,7 @@ def _readiness(
workflow_wait and review_age is not None
and -MAX_REVIEW_CLOCK_SKEW <= review_age < STALE_VERDICT_GRACE
),
publishers=publishers,
)
report = _load_report(wt)
receipt_problem = _check_report_problem(report, wt, config, head)
Expand Down Expand Up @@ -1704,17 +1705,20 @@ def _delete_tracking_ref(wt: Path, branch: str, expected_head: str) -> None:

def cmd_resolve(args: argparse.Namespace) -> int:
"""List open blocking findings, or reply to one with what changed and resolve its thread."""
wt, config = _context(args)
wt, config = _context(args, pin_checks=True) # publishers come from the base, not the PR
pr = _require_pr(config, worktree.branch(wt))
if pr.base_ref != config.base_branch: # trusted publishers belong to the configured base
raise CliError(f"PR #{pr.number} targets {pr.base_ref}, configured base is {config.base_branch}")
publishers = config.review_publishers or (github.login(),)
if not args.finding:
for marker_id, _thread, f in github.open_findings(config.repo, pr.number):
for marker_id, _thread, f in github.open_findings(config.repo, pr.number, publishers):
print(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}")
return 0
finding = github.resolve_finding(config.repo, pr.number, args.finding, args.reply)
finding = github.resolve_finding(config.repo, pr.number, args.finding, args.reply, publishers)
print(f"resolved {args.finding}: {finding.title}")
try:
with github.api_error_diagnostics():
remaining = github.open_blocking_findings(config.repo, pr.number)
remaining = github.open_blocking_findings(config.repo, pr.number, None, publishers)
except (github.GhError, _proc.ProcTimeout, OSError) as exc:
retry = shlex.join(("gh", *github.eligibility_dispatch_args(
config.repo, pr.number, config.base_branch,
Expand Down
5 changes: 3 additions & 2 deletions src/loopzero/eligibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def readiness_review(reviews: list[dict], head: str, publishers: tuple[str, ...]
verdict = summary.partition(": **")[2]
state = latest.get("state")
if verdict.startswith("request_changes** (") and state in {"CHANGES_REQUESTED", "COMMENTED"}:
if github.open_blocking_findings(repo, number, reviewed):
if github.open_blocking_findings(repo, number, reviewed, publishers):
return None
elif not (verdict.startswith("approve** (") and state in {"APPROVED", "COMMENTED"}):
return None
Expand Down Expand Up @@ -182,7 +182,8 @@ def evaluate(repo: str, number: int, head: str, base: str,
page += 1
review = readiness_review(reviews, head, publishers, repo=repo, number=number, base_branch=base)
result = github.readiness(repo, pr, base, (), head if review else None, allow_behind=True,
ancestor_review=review is not None and review["commit_id"] != head)
ancestor_review=review is not None and review["commit_id"] != head,
publishers=publishers)
if github.pr_view(repo, number).head_sha != head:
return github.Readiness(False, ("source head changed during eligibility refresh",))
return result
Expand Down
67 changes: 40 additions & 27 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,8 @@
_app_token_cache = ("", 0.0)
MISSING_REVIEW_REASON = "no review recorded for the current head"
MARKER_RE = re.compile(
r"<!--\s*loopzero:finding\s+(?:v=(?P<version>1)\s+)?"
r"severity=(?P<severity>\w+)(?:\s+head=(?P<head>[0-9a-fA-F]+))?"
r"(?:\s+id=(?P<id>[0-9a-fA-F]{8}))?\s*-->"
r"<!-- loopzero:finding v=1 severity=(?P<severity>\w+) "
r"head=(?P<head>[0-9a-f]{40}) id=(?P<id>[0-9a-f]{8}) -->"
)
PAGE = 100
PR_FILE_LIMIT = 3_000
Expand All @@ -50,7 +49,9 @@
pageInfo { hasNextPage endCursor }
nodes {
id isResolved isOutdated path line
comments(first: 1) { nodes { body } pageInfo { hasNextPage endCursor } }
comments(first: 1) {
nodes { body author { __typename login } } pageInfo { hasNextPage endCursor }
}
}
}
}
Expand Down Expand Up @@ -965,22 +966,29 @@ def _title_of(text: str) -> str:
return re.sub(r"^\*\*\w+:\s*|\*\*$", "", title_line).strip()


def _parse_thread(node: dict, current_head: str | None) -> Finding | None:
def _thread_marker(node: dict, publishers: tuple[str, ...]) -> re.Match[str] | None:
"""The v=1 marker opening a thread's first comment, if a review publisher wrote it."""
comments = node.get("comments", {}).get("nodes") or []
if not comments:
return None
first = comments[0]
body = first.get("body") or ""
match = MARKER_RE.search(body)
author = comments[0].get("author") or {}
login = str(author.get("login") or "")
# GraphQL names an App's bot account without REST's "[bot]" suffix.
if author.get("__typename") == "Bot":
login += "[bot]"
if not login or login.casefold() not in {p.casefold() for p in publishers}:
return None
# The publisher writes the marker as the whole first line, exactly as finding_marker does.
return MARKER_RE.fullmatch((comments[0].get("body") or "").partition("\n")[0])


def _parse_thread(node: dict, current_head: str | None,
publishers: tuple[str, ...]) -> Finding | None:
match = _thread_marker(node, publishers)
if not match or match.group("severity") not in BLOCKING:
return None
version = match.group("version")
body = node["comments"]["nodes"][0]["body"]
marker_head = match.group("head")
marker_id = match.group("id")
if version and (not marker_head or not marker_id):
return None
if not version and marker_id:
return None
if current_head is not None and marker_head != current_head and node.get("isOutdated"):
return None
severity = match.group("severity")
Expand All @@ -998,12 +1006,13 @@ def _parse_thread(node: dict, current_head: str | None) -> Finding | None:
)


def open_findings(repo: str, number: int) -> list[tuple[str, str, Finding]]:
def open_findings(repo: str, number: int,
publishers: tuple[str, ...]) -> list[tuple[str, str, Finding]]:
"""(marker id, thread id, finding) for every unresolved blocking thread, any head."""
return [
(MARKER_RE.search(node["comments"]["nodes"][0]["body"]).group("id") or node["id"], node["id"], f)
(_thread_marker(node, publishers).group("id"), node["id"], f)
for node in _unresolved_threads(repo, number)
if (f := _parse_thread(node, None))
if (f := _parse_thread(node, None, publishers))
]


Expand Down Expand Up @@ -1037,16 +1046,16 @@ def _has_thread_reply(node: dict, reply: str) -> bool:
return False


def resolve_finding(repo: str, number: int, finding_id: str, reply: str) -> Finding:
def resolve_finding(repo: str, number: int, finding_id: str, reply: str,
publishers: tuple[str, ...]) -> Finding:
"""Reply to a blocking finding, or resume an identical resolution."""
threads = _review_threads(repo, number, include_resolved=True)
for node in sorted(threads, key=lambda node: bool(node.get("isResolved"))):
finding = _parse_thread(node, None)
finding = _parse_thread(node, None, publishers)
if finding is None:
continue
marker = MARKER_RE.search(node["comments"]["nodes"][0]["body"])
thread_id = node["id"]
if (marker.group("id") or thread_id) != finding_id:
if _thread_marker(node, publishers).group("id") != finding_id:
continue
confirmed = _has_thread_reply(node, reply)
if node.get("isResolved"):
Expand Down Expand Up @@ -1093,15 +1102,17 @@ def refresh_eligibility(repo: str, number: int, base: str) -> None:


def open_blocking_findings(
repo: str, number: int, current_head: str | None = None
repo: str, number: int, current_head: str | None, publishers: tuple[str, ...],
) -> list[Finding]:
"""Findings from unresolved review threads whose first comment carries a blocking marker.
"""Findings from unresolved review threads whose first comment opens with a blocking marker.

Only explicit critical and important markers block. When `current_head` is supplied, an
outdated thread is ignored unless its marker names that head.
Only critical and important v=1 markers on the first line of a comment written by a
review publisher block. When `current_head` is supplied, an outdated thread is ignored
unless its marker names that head.
"""
return [
f for node in _unresolved_threads(repo, number) if (f := _parse_thread(node, current_head))
f for node in _unresolved_threads(repo, number)
if (f := _parse_thread(node, current_head, publishers))
]


Expand Down Expand Up @@ -1289,6 +1300,7 @@ def readiness(
review_grace: bool = False,
workflow_wait: bool = False,
stale_verdict_grace: bool = False,
publishers: tuple[str, ...],
) -> Readiness:
"""Decide whether `pr` may be marked ready / merged. Never raises on policy failures."""
reasons: list[str] = []
Expand All @@ -1304,7 +1316,8 @@ def readiness(
reasons.append(MISSING_REVIEW_REASON)
elif pr.head_sha != reviewed_head:
reasons.append(f"head {pr.head_sha[:12]} differs from reviewed {reviewed_head[:12]}")
for f in open_blocking_findings(repo, pr.number, None if ancestor_review else pr.head_sha):
for f in open_blocking_findings(repo, pr.number, None if ancestor_review else pr.head_sha,
publishers):
where = f"{f.path}:{f.line}" if f.path else "(no location)"
reasons.append(f"open {f.severity} finding at {where}: {f.title}")
checks, stale, stale_verdicts, capped = (_check_signals(
Expand Down
13 changes: 12 additions & 1 deletion src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,12 +260,23 @@ def merges_since(wt: Path, sha: str) -> list[str]:


def cleanup(wt: Path) -> None:
"""Remove the worktree and its branch. Refuses when the worktree is dirty."""
"""Remove the worktree and branch if there are no local user files."""
wt = Path(wt).absolute()
if not wt.exists():
raise WorktreeError(f"no such worktree: {wt}")
if is_dirty(wt):
raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}")
ignored = _git(
wt, "ls-files", "--others", "--ignored", "--exclude-standard", "-z", preserve_newlines=True
)
for path in ignored.split("\0")[:-1]:
if (
(path in {".loopzero/task.md", ".loopzero/checks.json"}
or re.fullmatch(r"\.loopzero/review-[0-9a-f]{12}-(primary|delta)\.json", path))
and not (wt / path).is_symlink()
):
continue
raise WorktreeError(f"worktree contains ignored file {path!r}, refusing to remove: {wt}")
name, gd = branch(wt), (wt / _git(wt, "rev-parse", "--git-common-dir")).resolve()
_git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout
try:
Expand Down
Loading
Loading