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
6 changes: 4 additions & 2 deletions core/skills/implement/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ and map each to a test or recorded evidence. Observe required UI/runtime behavio
proof for UI changes per [Reporting](../../CONTRACT.md#reporting). Required
acceptance that remains unobserved stays open
with a next-action owner. Record the tested revision, observations, trade-offs
and limits in Notes or human Validation. Follow the contract's
[gate receipt fields and reuse rules](../../CONTRACT.md#gate-execution-and-delivery-priority).
and limits in Notes or human Validation. Start primary review only with a
completed passing `loopzero check` receipt for the exact pushed head. Focused
tests and running checks are intermediate evidence. Reuse a passing same-head
receipt under the [contract's reuse rules](../../CONTRACT.md#gate-execution-and-delivery-priority).

Run commands expected to take more than about two minutes detached as in
[Long-running jobs](../../../docs/DELEGATION.md#long-running-jobs).
Expand Down
14 changes: 7 additions & 7 deletions core/skills/resolve-findings/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ security-path downgrades need requester authority. For conflicting findings,
reconcile their acceptance and impact. New critical evidence requires a separate
authorized PR review thread rather than silently expanding this batch.

After the delta, follow the contract's [round-two rule](../../CONTRACT.md#review-budget).
Return accepted repairs to delivery: fixing findings does not finish the task
until the fixed head is delivered.

Then continue the task you were given as far as it authorizes, or hand over
what is left of its acceptance. If two repairs have failed, the route is
probably wrong, so reconsider it before a third.
Before requesting the delta, compare the full repair with the primary-reviewed
head. Identify affected callers and guarantees for each repaired behavior. Use
existing test seams to exercise the failing case and any success, failure or
timing behavior the repair can change. Apply [security-review](../security-review/SKILL.md)
to changed trust boundaries. Record the evidence with the repair, run the
existing checks and follow the contract's [review budget](../../CONTRACT.md#review-budget)
through delivery or handoff of remaining acceptance.
6 changes: 4 additions & 2 deletions core/skills/work-issue/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ blueprint. Include required completion in the closing delivery. A child issue
does not own its parent's blueprint.
Recheck collisions before publication and again before merge, rereading live
acceptance, prior delivery and ownership. Reconcile changed state before proceeding.
Review, CI and observable post-merge acceptance waits remain this task;
neither bypass them nor start another issue.
On approval, run readiness at the approved head and defer suggestions and cleanup.
Before making a source edit for the [delta](../../CONTRACT.md#review-budget), name
the unmet acceptance criterion or newly verified defect that requires it.
Review, CI and post-merge acceptance waits remain this task.
Before using [CI or observation-based acceptance](reference.md#acceptance-evidence)
or [resuming after interruption or context loss](reference.md#re-entry),
follow the linked safeguards.
Expand Down
6 changes: 4 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +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.
reviews, finding threads, check statuses and merge state. PR body writers hold a same-host lock keyed by repository and PR from
the live read through the update, including writes from different checkouts.
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.
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
7 changes: 4 additions & 3 deletions scripts/size_budget.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ set -euo pipefail
# 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=8250
TESTS_CAP=13500
TESTS_CAP=13850
CORE_DOCS_CAP=1500
DELEGATION_DOC_CAP=660
COMPLEXITY_CAP=10
Expand Down Expand Up @@ -55,6 +55,7 @@ fi

"${PY[@]}" - "$base" src/loopzero "$COMPLEXITY_CAP" <<'PY' || status=1
import ast
import os
import subprocess
import sys
from pathlib import Path
Expand Down Expand Up @@ -122,14 +123,14 @@ base_scores: dict[tuple[str, str], int] = {}
for raw in git_bytes("ls-tree", "-rz", "--name-only", base, "--", target).split(b"\0"):
if not raw or not raw.endswith(b".py"):
continue
rel = raw.decode("utf-8", errors="surrogateescape")
rel = os.fsdecode(raw)
base_scores.update(file_complexities(rel, git_bytes("show", f"{base}:{rel}")))

tree_scores: dict[tuple[str, str], int] = {}
for raw in git_bytes("ls-files", "-zco", "--exclude-standard", "--", target).split(b"\0"):
if not raw or not raw.endswith(b".py"):
continue
rel = raw.decode("utf-8", errors="surrogateescape")
rel = os.fsdecode(raw)
p = Path(rel)
if p.is_file():
tree_scores.update(file_complexities(rel, p.read_bytes()))
Expand Down
81 changes: 40 additions & 41 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -542,14 +542,6 @@ def _append_review(body: str, result: ReviewResult) -> str:


def _refresh_pr_checks(wt: Path, config: Config) -> None:
try:
with _lock_task_state(wt):
_refresh_existing_pr_checks(wt, config)
except OSError as exc:
print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr)


def _refresh_existing_pr_checks(wt: Path, config: Config) -> None:
"""Best-effort refresh only when local HEAD is the existing PR head."""
argv = ["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]
try:
Expand All @@ -559,7 +551,10 @@ def _refresh_existing_pr_checks(wt: Path, config: Config) -> None:
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:
_update_pr_checks(wt, head, config, pr)
with github.pr_lock(config.repo, pr.number):
live = github.pr_view(config.repo, pr.number)
if live.state == "OPEN" and live.head_sha == head:
_update_pr_checks(wt, head, config, live)
except (github.GhError, _proc.ProcTimeout, OSError, ValueError, CliError) as exc:
print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr)

Expand Down Expand Up @@ -669,7 +664,7 @@ def cmd_pr(args: argparse.Namespace) -> int:
push.append(branch)
_git_push(wt, push, force_lease=force_lease)
if pr is not None and pr.state == "OPEN":
with _lock_task_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 @@ -795,21 +790,14 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
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,
confirmed, _ = _recover_review(wt, config, pr, result,
publication["publisher"], token)
if confirmed:
return _finish_review(wt, config, pr, result)
else:
reviews = _pr_reviews(config.repo, pr.number)
return _finish_review(config, pr, result)
# Exact read-back above may confirm an older published note; a new post needs the current form.
candidates = [family for family in config.reviewers if family not in authors]
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, _ = _decide_kind(
_pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head
)
if allowed != kind:
raise CliError("saved review kind differs from the remaining review budget")
else:
try:
result = _run_review(wt, config, head, kind, reviewed, args.model, args.effort,
Expand All @@ -835,30 +823,32 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
prefix = _repost_prefix(result)
_save_review(wt, result, {"repo": config.repo, "number": pr.number, "publisher": publisher})
token = _refresh_publisher_token(token, publisher)
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)
with github.pr_lock(config.repo, pr.number):
_require_open_review_round(config, pr, head, kind)
try:
if _recover_review(wt, config, pr, result, publisher, token)[0]:
return _finish_review(wt, config, pr, 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
return _finish_review(wt, config, pr, result)


def _finish_review(wt: Path, config: Config, pr: github.PR, result: ReviewResult) -> int:
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:
confirmed, _ = _recover_review(wt, config, pr, result, publisher, token)
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
if not confirmed:
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
return _finish_review(config, pr, result)


def _finish_review(config: Config, pr: github.PR, result: ReviewResult) -> int:
try:
with _lock_task_state(wt):
with github.pr_lock(config.repo, pr.number):
live = github.pr_view(config.repo, pr.number)
body = _append_review(live.body, result)
if body != live.body:
Expand All @@ -868,6 +858,15 @@ def _finish_review(wt: Path, config: Config, pr: github.PR, result: ReviewResult
return _review_verdict(result)


def _require_open_review_round(config: Config, pr: github.PR, head: str, kind: str) -> None:
markers = _pr_markers(_pr_reviews(config.repo, pr.number), 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 _decide_kind(markers, head)[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:
Expand Down
12 changes: 12 additions & 0 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import fcntl
import hashlib
import json
import os
Expand All @@ -25,6 +26,7 @@

GH_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GH_TOKEN", "GITHUB_TOKEN", "GH_HOST")
APP_TOKEN_HELPER = Path.home() / ".config/loopzero/app-token"
PR_LOCK_DIR = Path.home() / ".cache/loopzero/pr-locks"
_app_token_cache = ("", 0.0)
MISSING_REVIEW_REASON = "no review recorded for the current head"
MARKER_RE = re.compile(
Expand Down Expand Up @@ -263,6 +265,16 @@ def _cached_app_token() -> str:
return token if token and 0 <= time.time() - minted < 3000 else ""


@contextmanager
def pr_lock(repo: str, number: int) -> Iterator[None]:
"""Serialize a GitHub write across local checkouts for this PR."""
key = hashlib.sha256(f"{repo.casefold()}#{number}".encode()).hexdigest()
PR_LOCK_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
with (PR_LOCK_DIR / key).open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
yield


def app_token() -> str:
global _app_token_cache
if token := _cached_app_token():
Expand Down
54 changes: 22 additions & 32 deletions src/loopzero/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,11 @@ def _extract_json_object(text: str) -> object:
return json.loads(stripped[start : end + 1])


def _claude_payload(envelope: dict) -> object:
payload = envelope.get("structured_output")
return _extract_json_object(str(envelope.get("result", ""))) if payload is None else payload


def parse_review(payload: object, *, family: str, head: str, kind: str, raw: str) -> ReviewResult:
"""Validate a decoded review object against the findings schema."""
if not isinstance(payload, dict):
Expand Down Expand Up @@ -930,22 +935,16 @@ def _codex_evidence(result):
or sum(e.get("type") == "turn.completed" for e in events) != 1
):
raise RunnerBadOutput("codex: incomplete/mixed native terminal evidence")
final = [
e.get("item", {}).get("text")
for e in events
messages = [
(i, e["item"].get("text"))
for i, e in enumerate(events)
if e.get("type") == "item.completed"
and isinstance(e.get("item"), dict)
and e["item"].get("type") == "agent_message"
]
if not final or _evidence_json(final[-1]) != _evidence_json(envelope["final_message"]):
if not messages or _evidence_json(messages[-1][1]) != _evidence_json(envelope["final_message"]):
raise RunnerBadOutput("codex: native final verdict is missing")
last_message = max(
i
for i, e in enumerate(events)
if e.get("type") == "item.completed"
and isinstance(e.get("item"), dict)
and e["item"].get("type") == "agent_message"
)
last_message = messages[-1][0]
if any(
e.get("type") == "item.completed"
and e.get("item", {}).get("type") == "command_execution"
Expand Down Expand Up @@ -1159,12 +1158,10 @@ def _review_claude(
if _looks_too_long(text) or _looks_too_long(raw):
raise RunnerPromptTooLong("claude: prompt is too long", _tail(raw))
raise RunnerBadOutput(f"claude: {envelope.get('subtype', 'error')}", _tail(raw))
payload = envelope.get("structured_output")
if payload is None:
try:
payload = _extract_json_object(str(envelope.get("result", "")))
except (json.JSONDecodeError, ValueError) as exc:
raise RunnerBadOutput("claude: result text is not JSON", _tail(raw)) from exc
try:
payload = _claude_payload(envelope)
except (json.JSONDecodeError, ValueError) as exc:
raise RunnerBadOutput("claude: result text is not JSON", _tail(raw)) from exc
usage = envelope.get("modelUsage")
models = tuple(key for key in usage if isinstance(key, str)) if isinstance(usage, dict) else ()
reported_model = ", ".join(models) or None
Expand Down Expand Up @@ -1307,11 +1304,10 @@ def review_with(
"""Run one review of ``diff`` at ``head`` with the given model family."""
if family not in REVIEWER_FAMILIES:
raise ValueError(f"unknown reviewer family {family!r}; expected one of {REVIEWER_FAMILIES}")
if kind not in ("primary", "delta"):
raise ValueError(f"unknown review kind {kind!r}; expected 'primary' or 'delta'")
policy = _review_policy(kind, split=chunk is not None)
prompt = build_prompt(kind=kind, head=head, task_text=task_text, diff=diff, chunk=chunk)
adapter = _review_claude if family == "claude" else _review_codex
policy, extra = _review_policy(kind, split=chunk is not None), {}
extra = {}
if family == "codex" and review_context is not None:
context = {**review_context, "cwd": str(cwd.resolve()), "index": chunk[0] if chunk else 1,
"chunks": chunk[1] if chunk else 1, "requested": {"model": model, "effort": effort},
Expand Down Expand Up @@ -1471,22 +1467,16 @@ def validate_runner_result(result: ReviewResult) -> bool:
and all(item.get("subtype", "success") == "success" for item in envelopes)
and all(not item.get("is_error") for item in envelopes)
and all(isinstance(item, dict) for item in usages)
and all(isinstance(item, (int, float)) and not isinstance(item, bool) for item in costs)
and all(
isinstance(item, (int, float)) and not isinstance(item, bool)
for item in durations
)
and all(isinstance(item, (int, float)) and not isinstance(item, bool)
for item in costs + durations)
and provenance.get("usage") == expected_usage
and provenance.get("total_cost_usd") == sum(costs)
and provenance.get("duration_api_ms") == sum(durations)
)
payloads = [item.get("structured_output") for item in envelopes]
for index, payload in enumerate(payloads):
if payload is None:
try:
payloads[index] = _extract_json_object(str(envelopes[index].get("result", "")))
except (json.JSONDecodeError, ValueError):
return False
try:
payloads = [_claude_payload(item) for item in envelopes]
except (json.JSONDecodeError, ValueError):
return False
elif result.family == "codex":
envelope_sessions = [item.get("session_id") for item in envelopes]
usages = [item.get("token_usage") for item in envelopes]
Expand Down
1 change: 1 addition & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

@pytest.fixture(autouse=True)
def no_real_app_helper(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(github, "PR_LOCK_DIR", tmp_path / "pr-locks")
monkeypatch.setattr(github, "APP_TOKEN_HELPER", tmp_path / "absent-app-token", raising=False)
monkeypatch.setattr(github, "_app_token_cache", ("", 0.0), raising=False)

Expand Down
Loading
Loading