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
11 changes: 7 additions & 4 deletions scripts/check_architecture_docs.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Offline architecture links and public-interface review gate; see docs/ARCHITECTURE.md."""
import argparse
import ast
import os
import re
import subprocess
import sys
Expand All @@ -21,9 +22,9 @@
}


def git(root, *args):
def git(root, *args, text=True):
return subprocess.run(["git", *args], cwd=root, check=True,
capture_output=True, text=True).stdout
capture_output=True, text=text).stdout


def interface(text, names):
Expand Down Expand Up @@ -75,8 +76,10 @@ def link_errors(root):

def check(root, base):
git(root, "rev-parse", "--verify", f"{base}^{{commit}}")
changed = set(git(root, "diff", "--name-only", "-z", base).split("\0"))
changed.update(git(root, "ls-files", "--others", "--exclude-standard", "-z").split("\0"))
tracked = git(root, "diff", "--name-only", "-z", base, text=False)
untracked = git(root, "ls-files", "--others", "--exclude-standard", "-z", text=False)
changed = set(os.fsdecode(tracked).split("\0"))
changed.update(os.fsdecode(untracked).split("\0"))
watched = changed.intersection(WATCHED)
watched.update(p for p in changed if p.startswith(".github/workflows/"))
for name, names in INTERFACES.items():
Expand Down
4 changes: 2 additions & 2 deletions scripts/size_budget.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
# it under the cap.
# Usage: scripts/size_budget.sh [BASE] (default: merge-base with origin/main)
set -euo pipefail
# Measured 2026-11-10: 6777 source lines.
# Measured 2026-11-26: 7494 source lines.
# Measured 2026-11-25: 12289 test lines.
# Measured 2026-11-25: 1406 core Markdown / 600 delegation Markdown lines.
# Allow ~10% growth, rounded up, so small fixes do not require cap changes.
SRC_CAP=7500
SRC_CAP=8250
TESTS_CAP=13500
CORE_DOCS_CAP=1500
DELEGATION_DOC_CAP=660
Expand Down
7 changes: 4 additions & 3 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ def _pr_markers(reviews: list[dict], head: str,
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 = REVIEW_MARKER_RE.search(body)
match = eligibility.leading_marker(body)
if not match or review.get("commit_id") != match.group(1):
continue
if not trusted:
Expand Down Expand Up @@ -894,8 +894,9 @@ def _confirm_review(wt: Path, config: Config, pr: github.PR, result: ReviewResul
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 any(
m.group(1) == result.head for m in REVIEW_MARKER_RE.finditer(r["body"])))]
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:
raise CliError("PR changed during publication recovery")
Expand Down
16 changes: 12 additions & 4 deletions src/loopzero/eligibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@
CONTEXT = "Loop-zero Eligibility"


def leading_marker(body: str) -> re.Match[str] | None:
"""The review marker opening the publisher's leading machine block; prose never counts."""
block, span = runners.leading_review_block(body if isinstance(body, str) else "")
if not block or len(REVIEW_MARKER_RE.findall(span)) != 1:
return None
return REVIEW_MARKER_RE.fullmatch(block[0])


def review_envelopes(body: str) -> tuple[str, list[dict]]:
"""Decode only the publisher's raw-output block, not quoted findings/prose."""
if not isinstance(body, str):
Expand All @@ -40,7 +48,7 @@ def review_projection(review: dict, head: str, repo: str, number: int):
block, span = runners.leading_review_block(body)
positions = [i for i, line in enumerate(block) if line.lstrip().startswith("<!-- loopzero:codex-evidence")]
# Retired pair markers must never fall back to ordinary review evidence.
if any("source=pair" in marker[0] for marker in REVIEW_MARKER_RE.finditer(body)):
if any("source=pair" in marker[0] for marker in REVIEW_MARKER_RE.finditer(span)):
return True, None
if not positions:
return False, None
Expand Down Expand Up @@ -72,8 +80,8 @@ def eligible_review(reviews: list[dict], head: str, publishers: tuple[str, ...],
if latest is None or latest.get("state") not in {"APPROVED", "COMMENTED", "CHANGES_REQUESTED"}:
return None
body = latest.get("body") or ""
matches = list(REVIEW_MARKER_RE.finditer(body))
if len(matches) != 1 or matches[0].group(1) != head or not re.fullmatch(r"[0-9a-f]{40}", head):
marker = leading_marker(body)
if not marker or marker.group(1) != head or not re.fullmatch(r"[0-9a-f]{40}", head):
return None
verdict = latest.get("state") in {"APPROVED", "CHANGES_REQUESTED"} or any(
f"**{value}**" in body for value in ("approve", "request_changes")
Expand Down Expand Up @@ -126,7 +134,7 @@ def readiness_review(reviews: list[dict], head: str, publishers: tuple[str, ...]
if not marked or any(r.get("commit_id") == head for r in marked):
return eligible_review(marked, head, publishers, repo=repo, number=number)
latest = marked[-1]
marker = REVIEW_MARKER_RE.search(latest["body"])
marker = leading_marker(latest["body"])
if not marker or marker[2] not in {"primary", "delta"}:
return None
reviewed = marker[1]
Expand Down
19 changes: 19 additions & 0 deletions tests/test_architecture_docs.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Exercise the documentation check as a contributor/CI subprocess in real Git."""
import os
import subprocess
import sys
from pathlib import Path
Expand Down Expand Up @@ -26,6 +27,24 @@ def run(repo, base, *args):
text=True, capture_output=True, check=False)


@pytest.mark.skipif(sys.platform != "linux", reason="requires raw pathname bytes")
@pytest.mark.parametrize("staged", [False, True])
def test_architecture_check_accepts_non_utf8_path(git_repo, staged):
base = prepare(git_repo)
path = os.fsdecode(b"caf\xe9.txt")
(git_repo / path).write_text("unrelated file\n")
if staged:
git(git_repo, "add", "--", path)

done = run(git_repo, base)
assert done.returncode == 0, done.stderr

(git_repo / "core/CONTRACT.md").write_text("# New authority\n")
done = run(git_repo, base)
assert done.returncode == 1
assert "without guide update or reasoned Architecture-Review trailer" in done.stderr


@pytest.mark.parametrize("sync", ["missing", "guide", "trailer", "empty", "squash"])
def test_architecture_change_requires_update_or_reasoned_review(git_repo, sync):
base = prepare(git_repo)
Expand Down
40 changes: 39 additions & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

from loopzero import cli, config, github, mergify
from loopzero._proc import Completed, build_env
from loopzero.types import CheckReport, CheckResult, ReviewResult
from loopzero.types import CheckReport, CheckResult, Finding, ReviewResult
from tests.conftest import git, init_git_repo
from tests.fake_gh import replay
from tests.test_github import (
Expand Down Expand Up @@ -198,6 +198,44 @@ def test_review_marker_parser_accepts_old_and_v1_forms() -> None:
assert cli.REVIEW_MARKER_RE.search(new).groups() == ("b" * 40, "delta")


@pytest.mark.parametrize("source", ["model", "pair"])
def test_review_marker_quoted_in_prose_neither_voids_nor_hides_a_review(gh: FakeGh, source: str) -> None:
head = "a" * 40
quote = cli.review_marker("b" * 40, "primary", source)
result = ReviewResult("claude", head, "primary", "approve",
(Finding("suggestion", None, None, "Fixture", f"The fixture quotes {quote}."),),
"raw", provenance={"session_ids": ["s"]})
gh.respond(f"api repos/{REPO}/pulls/7/files", [])
(payload,) = github.review_payloads(REPO, 7, head, result, [(marker(head, "primary"), "current", False)])
review = {"body": payload["body"], "state": "COMMENTED", "commit_id": head, "user": {"login": LOGIN}}
assert quote in review["body"]

assert cli.eligibility.eligible_review([review], head, (LOGIN,)) is review
assert cli.eligibility.readiness_review(
[review], head, (LOGIN,), repo=REPO, number=7, base_branch="main") is review
assert cli._pr_markers([review], head, (LOGIN,)) == [cli.Marker(head, "primary", "COMMENTED")]


def test_second_review_marker_in_the_leading_block_voids_the_review() -> None:
head = "a" * 40
body = f"{marker(head, 'primary')}\n{marker('b' * 40, 'primary')}\nreview: **approve**"
review = {"body": body, "state": "APPROVED", "commit_id": head, "user": {"login": LOGIN}}
assert cli.eligibility.eligible_review([review], head, (LOGIN,)) is None
assert cli.eligibility.readiness_review(
[review], head, (LOGIN,), repo=REPO, number=7, base_branch="main") is None
assert cli._pr_markers([review], head, (LOGIN,)) == []


def test_publication_recovery_ignores_markers_quoted_on_other_commits(wt: Path, gh: FakeGh, head) -> None:
config = cli.config_mod.load(wt / "workflow.toml")
result = ReviewResult("claude", head, "primary", "approve", (), "raw", provenance={"session_ids": ["s"]})
other = rev("f" * 40, "primary")
other["body"] += f"\nA finding quotes {marker(head, 'primary')}"
gh.respond_pr_view(pr_json(headRefOid=head))
pr = github.PR(7, URL, head, "main", False, "OPEN", "MERGEABLE")
assert cli._confirm_review(wt, config, pr, result, LOGIN, [other]) is False


def rev(head: str, kind: str, *, state: str = "APPROVED", commit: str | None = None,
login: str = LOGIN, verdict: str = "approve") -> dict:
"""A review object as `gh api .../reviews` returns it, carrying a loopzero marker."""
Expand Down
Loading