Skip to content
8 changes: 4 additions & 4 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ local-receipt exceptions. Merge authority permits merging by default outside
reserved classes.

Git owns commits, branches and ancestry. GitHub owns the live PR narrative,
reviews, finding threads, check statuses and merge state. Within a task worktree,
PR body writers lock the state directory from the live read through the update.
Review publication rechecks the round while holding a same-host lock keyed by
repository and PR. The lock covers POST and lost-response read-back.
reviews, finding threads, check statuses and merge state. PR body writers hold
the same-host repository-and-PR lock from the live read through the update.
Review publication holds that lock for its round recheck, POST, read-back, and
body summary. Check coalescing and receipts retain the worktree-local lock.
CI and branch protection
provide the hosted enforcement. Readiness is a checklist over these sources,
not a tamper-proof security boundary: repository writers can edit PR evidence,
Expand Down
32 changes: 18 additions & 14 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -572,15 +572,20 @@ def _append_review(body: str, result: ReviewResult) -> str:
def _refresh_pr_checks(wt: Path, config: Config) -> None:
"""Best-effort refresh only when local HEAD is the existing PR head."""
try:
with worktree.lock_local_state(wt):
upstream = config_mod.run_git(wt, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}")
if upstream.exit_code == 0:
branch, head = worktree.branch(wt), worktree.head(wt)
pr = github.pr_for_branch(config.repo, branch, open_only=True)
if pr is not None and pr.head_sha == head:
body = _pr_body(wt, head, config, pr.body)
if body != (pr.body or "").replace("\r\n", "\n"):
github.update_body(config.repo, pr.number, body)
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)

Expand Down Expand Up @@ -727,7 +732,7 @@ def cmd_pr(args: argparse.Namespace) -> int:
_require_push_target(wt, config.repo)
_git_push(wt, push, force_lease=force_lease)
if pr is not None:
with worktree.lock_local_state(wt):
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")
Expand Down Expand Up @@ -888,12 +893,11 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
f"{exc} | publication unconfirmed; review saved at {path}; "
"inspect the cause and run `loopzero review --repost` to reconcile or explicitly retry"
) from exc
try:
with worktree.lock_local_state(wt):
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)
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)


Expand Down
78 changes: 34 additions & 44 deletions src/loopzero/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"review_chunk_bytes": int, "review": dict,
},
}
_REVIEW_SETTINGS = {"model": str, "effort": str, "allowed_efforts": list}


class ConfigError(LoopZeroError):
Expand Down Expand Up @@ -151,64 +152,44 @@ def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: boo

def _build(data: dict[str, Any]) -> Config:
_reject_unknown("top level", data, _SECTIONS)
for section, keys in _SECTIONS.items():
table = data.get(section, {})
if not isinstance(table, dict):
raise ConfigError(f"[{section}] must be a table")
_reject_unknown(f"[{section}]", table, keys)
for key, kind in keys.items():
if key in table and not isinstance(table[key], kind):
raise ConfigError(f"{section}.{key} must be a {kind.__name__}")

repo = data.get("repo", {})
checks = data.get("checks", {})
delivery = data.get("delivery", {})

if "name" not in repo:
sections = {
section: _check_table(section, data.get(section, {}), schema)
for section, schema in _SECTIONS.items()
}
repo, checks, delivery = sections["repo"], sections["checks"], sections["delivery"]

if (name := repo.get("name")) is None:
raise ConfigError("missing required key repo.name (\"owner/name\")")
name = repo["name"]
if name.count("/") != 1 or not all(name.split("/")):
raise ConfigError(f'repo.name must look like "owner/name", got {name!r}')

base = repo.get("base", "main")
if not base:
if not (base := repo.get("base", "main")):
raise ConfigError("repo.base must not be empty")
merge, mergify_queue = _merge_settings(delivery)
reviewers = _strings("delivery.reviewers", delivery.get("reviewers", list(REVIEWER_FAMILIES)))
if not reviewers:
raise ConfigError("delivery.reviewers must list at least one reviewer")
for reviewer in reviewers:
if reviewer not in REVIEWER_FAMILIES:
raise ConfigError(
f"delivery.reviewers entries must be in {REVIEWER_FAMILIES}, got {reviewer!r}"
)
review_chunk_bytes = delivery.get("review_chunk_bytes", 200_000)
if unknown := next((family for family in reviewers if family not in REVIEWER_FAMILIES), None):
raise ConfigError(f"delivery.reviewers entries must be in {REVIEWER_FAMILIES}, got {unknown!r}")
review_chunk_bytes = delivery.get("review_chunk_bytes", Config.review_chunk_bytes)
if isinstance(review_chunk_bytes, bool) or review_chunk_bytes < 4096:
raise ConfigError("delivery.review_chunk_bytes must be an int >= 4096")
review: dict[str, ReviewConfig] = {}
for family, table in delivery.get("review", {}).items():
if family not in REVIEWER_FAMILIES:
raise ConfigError(f"unknown review family delivery.review.{family}")
if not isinstance(table, dict):
raise ConfigError(f"[delivery.review.{family}] must be a table")
label = f"delivery.review.{family}"
_reject_unknown(f"[{label}]", table, ("model", "effort", "allowed_efforts"))
for key in ("model", "effort"):
if key in table and (not isinstance(table[key], str) or not table[key]):
raise ConfigError(f"{label}.{key} must be a non-empty str")
allowed = table.get("allowed_efforts", [])
if not isinstance(allowed, list):
raise ConfigError(f"{label}.allowed_efforts must be a list")
review[family] = ReviewConfig(table.get("model"), table.get("effort"),
_strings(f"{label}.allowed_efforts", allowed))
table = _check_table(label, table, _REVIEW_SETTINGS, nonempty_strings=True)
review[family] = ReviewConfig(
table.get("model"), table.get("effort"), _strings(f"{label}.allowed_efforts", table.get("allowed_efforts", [])),
)

commands = _strings("checks.commands", checks.get("commands", []))
if any(not command.strip() for command in commands):
raise ConfigError("checks.commands entries must each be a nonblank command")
kwargs: dict[str, Any] = {}
if "runner" in checks:
runner = _strings("checks.runner", checks["runner"])
if not runner or any(not arg or "\0" in arg for arg in runner):
if not (runner := _strings("checks.runner", checks["runner"])) or any("\0" in arg for arg in runner):
raise ConfigError("checks.runner must be a nonempty argv prefix")
if "/" in runner[0] and not Path(runner[0]).is_absolute():
raise ConfigError("checks.runner executable paths must be absolute")
Expand Down Expand Up @@ -236,10 +217,8 @@ def _build(data: dict[str, Any]) -> Config:
if "runner" in checks and checks["limits"]:
keys = ", ".join(f"checks.limits.{key}" for key in sorted(checks["limits"]))
raise ConfigError(f"{keys} apply only to local checks and cannot be set with checks.runner")
reviewer_ro_paths = _host_paths(
"delivery.reviewer_ro_paths", delivery.get("reviewer_ro_paths", [])
)
return Config(
reviewer_ro_paths=_host_paths("delivery.reviewer_ro_paths", delivery.get("reviewer_ro_paths", [])),
repo=name,
base_branch=base,
checks=commands,
Expand All @@ -250,16 +229,14 @@ def _build(data: dict[str, Any]) -> Config:
review_publishers=_strings("delivery.review_publishers",
delivery.get("review_publishers", [])),
review=review,
reviewer_ro_paths=reviewer_ro_paths,
review_chunk_bytes=review_chunk_bytes,
network=checks.get("network", False),
inputs=inputs, env=env, **kwargs,
)


def _merge_settings(delivery: dict[str, Any]) -> tuple[str, str | None]:
merge = delivery.get("merge", "squash")
if merge not in MERGE_STRATEGIES:
if (merge := delivery.get("merge", "squash")) not in MERGE_STRATEGIES:
raise ConfigError(f"delivery.merge must be one of {MERGE_STRATEGIES}, got {merge!r}")
mergify_queue = delivery.get("mergify_queue")
if merge == "mergify":
Expand All @@ -272,9 +249,22 @@ def _merge_settings(delivery: dict[str, Any]) -> tuple[str, str | None]:
return merge, mergify_queue


def _check_table(label: str, table: Any, schema: dict[str, type], *,
nonempty_strings: bool = False) -> dict[str, Any]:
if not isinstance(table, dict):
raise ConfigError(f"[{label}] must be a table")
_reject_unknown(f"[{label}]", table, schema)
for key, kind in schema.items():
if key in table:
nonempty = nonempty_strings and kind is str
if not isinstance(table[key], kind) or (nonempty and not table[key]):
expected = "non-empty str" if nonempty else kind.__name__
raise ConfigError(f"{label}.{key} must be a {expected}")
return table


def _reject_unknown(where: str, table: dict[str, Any], allowed: Any) -> None:
unknown = sorted(set(table) - set(allowed))
if unknown:
if unknown := sorted(set(table) - set(allowed)):
raise ConfigError(f"unknown key(s) in {where}: {', '.join(unknown)}")


Expand Down
Loading
Loading