Skip to content
Closed
44 changes: 22 additions & 22 deletions core/CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,21 @@ own delivery state; `.loopzero/` holds task text and local receipts.
problem, context, acceptance, base SHA. Write the PR, like any issue or
design doc you write, for the project owner under [Reporting](#reporting).
2. Implement, commit, then `loopzero check`: run `workflow.toml`
`[checks].commands` in the sandbox. Its exit code is the verdict. For a long
check under a [provider-portable handoff](../docs/DELEGATION.md#provider-portable-handoff),
open the draft in step 3 before starting the check.
`[checks].commands` in the sandbox. Open the draft before a long check under a
[provider-portable handoff](../docs/DELEGATION.md#provider-portable-handoff).
3. `loopzero pr` pushes and opens a **draft** PR from the task text plus
generated Validation checks. Later calls sync narrative, preserving live
Validation, Review and extra sections; `check` refreshes only its checks
block. Drafts need no clean review.
4. `loopzero review` reviews the exact head, independently by default, and
posts one GitHub review with inline findings: exit 0 `approve`,
5 `request_changes`.
5. `loopzero ready --wait` marks ready PRs ready for review. It also activates
drafts blocked only by missing/skipped checks to trigger CI, even with
mergeability pending. Without waiting, activation exits 3.
Both waiters use `--wait[=SECONDS]` (default 1800) on the unchanged head.
Zero seconds can still activate or enqueue a PR. Pending mergeability can
time out (exit 3) with green checks. `loopzero merge --cancel` requests
Mergify removal without `--wait`.
Green can precede CI scheduling. After two minutes with only missing checks
and none pending, inspect scheduling, triggers and permissions, then retry.
4. `loopzero review` defaults to independent review of the exact head and posts
one GitHub review with inline findings. Approval exits 0, changes requested 5.
5. `loopzero ready --wait` marks eligible PRs ready and activates drafts with
only missing/skipped checks even with mergeability pending. Activation without a
wait exits 3. Both waiters use `--wait[=SECONDS]` (default 1800) on the same
head. Zero can activate or enqueue. Mergeability can time out (exit 3)
with green checks. `loopzero merge --cancel` requests Mergify removal without `--wait`.
Green can precede CI scheduling. After two minutes of missing checks with
none pending, inspect scheduling, triggers and permissions, then retry.
6. After step 5 exits 0, run from a durable directory such as `/tmp`
using the absolute path to the task worktree.

Expand All @@ -37,10 +33,9 @@ own delivery state; `.loopzero/` holds task text and local receipts.
```

Merge rechecks readiness, uses the configured strategy, verifies the landed
SHA, and deletes the branch and worktree. If cleanup warns, the merge landed.
Follow the recovery step it names. A queue initially enqueues;
`--wait` shares a budget across source-check and landing waits. Enqueueing
without `--wait` returns 0 without cleanup.
SHA and deletes the branch and worktree. A cleanup warning follows a verified
merge. Follow its recovery step. Queueing without `--wait` exits 0 without
cleanup. With `--wait`, source checks and landing share one budget.

Merge is authorized by default under [merge authority](#merge-authority).

Expand Down Expand Up @@ -283,9 +278,14 @@ meta-directives; reviewers load no instruction files or skills from the reviewed

## Failure

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.
Fail closed on missing tools or command errors. Preserve the command and output
tail, name the cause or stage safely, and stop on terminal failures or quota errors.
`check` exits 0 when stages pass, including local dirty runs that cannot satisfy
readiness. Exit 1 can mean a failed stage, a discarded or unverified result, or
a command error. Read the diagnostic and verify the receipt before classifying
the failure. Exit 2 covers invalid arguments and sandbox unavailability in
`check` or fresh `review`.

Exit 3 means waiting or timeout. Review exits 4 when independent review is
unavailable and 5 when changes are requested. Interruption exits 130.

Expand Down
78 changes: 55 additions & 23 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -813,24 +813,10 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
kind, reviewed = _decide_kind(
_pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head
)
publication_context = {"repo": config.repo, "number": pr.number, "publisher": publisher}
if args.repost:
authors = runners.author_families(wt, head, _primary_base(wt, config))
excluded = [family for family in config.reviewers if family in authors]
result = _load_review(wt, head, kind)
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 any(family not in authors for family in config.reviewers):
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"
)
candidates, excluded = _repost_reviewer_families(wt, config, head, result)
publication = json.loads(_review_file(wt, head, kind).read_text()).get("publication")
if publication is not None:
if (not isinstance(publication, dict) or publication.get("repo") != config.repo
Expand All @@ -845,7 +831,6 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
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.
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(
Expand All @@ -854,6 +839,10 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
if allowed != kind:
raise CliError("saved review kind differs from the remaining review budget")
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`")
try:
result = _run_review(wt, config, head, kind, reviewed, args.model, args.effort,
runtime_source=runtime_source, publication=(config.repo, pr.number, publisher))
Expand All @@ -876,7 +865,7 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int:
raise CliError("native publication context changed; HOLD")
if args.repost:
prefix = _repost_prefix(result)
_save_review(wt, result, {"repo": config.repo, "number": pr.number, "publisher": publisher})
_save_review(wt, result, publication_context)
token = _refresh_publisher_token(token, publisher)
try:
github.post_review(
Expand Down Expand Up @@ -922,6 +911,47 @@ def _review_verdict(result: ReviewResult) -> int:
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))
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 any(family not in authors for family in config.reviewers):
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 [family for family in config.reviewers if family not in authors], excluded


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)
if result.fallback and not _published_fallback(result.fallback, candidates, excluded):
return False
evidence = runners.codex_evidence(result)
except (CliError, runners.RunnerBadOutput):
return False
return evidence is None or (evidence["repo"], evidence["pr"], evidence["publisher"]) == (
publication["repo"], publication["number"], publication["publisher"],
)


def _repost_prefix(result: ReviewResult) -> str:
sessions = result.provenance["session_ids"]
return review_marker(result.head, result.kind, "repost") + "\n" + (
Expand Down Expand Up @@ -1153,22 +1183,24 @@ def _save_review(wt: Path, result: ReviewResult, publication: dict | None = None
_write_json_atomically(directory, path.name, data)


def _load_review(wt: Path, head: str, kind: str) -> ReviewResult:
def _load_review(
wt: Path, head: str, kind: str, *, publication: dict | None = None,
) -> ReviewResult:
path = _review_file(wt, head, kind)
if not path.exists():
raise CliError(f"no saved {kind} review for {head[:12]} at {path}; run without --repost")
try:
data = json.loads(path.read_text())
except (json.JSONDecodeError, OSError) as exc:
except (ValueError, OSError) as exc:
raise CliError(f"{path} is not runner-produced: invalid saved review") from exc
if not isinstance(data, dict):
raise CliError(f"{path} is not runner-produced: invalid saved review")
if data.get("head") != head:
raise CliError(f"{path} holds a review of {str(data.get('head'))[:12]}, not HEAD {head[:12]}")
try:
data.pop("publication", None)
if data.get("kind") != kind:
raise ValueError("saved review kind mismatch")
saved_publication = data.pop("publication", None)
if data.get("kind") != kind or (publication is not None and saved_publication != publication):
raise ValueError("saved review kind or publication mismatch")
findings = tuple(Finding(**f) for f in data["findings"])
# Ordinary receipts written before pair retirement still carry these defaults.
for field, default in (("members", []), ("reconciliation", ""),
Expand Down
61 changes: 27 additions & 34 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ def helper(tmp_path, monkeypatch):
return module


@pytest.fixture
def exec_envs(helper, monkeypatch):
children = []
monkeypatch.setattr(helper.os, 'execvpe', lambda command, args, env: children.append(env))
return children


@pytest.mark.parametrize('provider,key', [('claude', 'CLAUDE_CODE_OAUTH_TOKEN'), ('codex', 'CODEX_HOME')])
def test_managed_credentials_rebind_and_preserve_explicit(helper, provider, key):
if provider == 'codex':
Expand Down Expand Up @@ -124,7 +131,7 @@ def test_stale_failure_requires_exact_model_evidence(helper, monkeypatch, cache,
assert helper.active('claude') == active


def test_launch_then_pin_survives_active_change(helper, monkeypatch, capsys):
def test_launch_then_pin_survives_active_change(helper, monkeypatch, capsys, exec_envs):
monkeypatch.setattr(helper, 'probe_claude_model', lambda token, model: {'ok': True, 'http': 200, 'util': {}})
assert helper.main(['launch', 'claude', '--model', 'm']) == 0
output = capsys.readouterr().out
Expand All @@ -135,26 +142,22 @@ def test_launch_then_pin_survives_active_change(helper, monkeypatch, capsys):
monkeypatch.setattr(helper, 'probe_claude_model', lambda *args: pytest.fail('cached launch probed'))
assert helper.launch('claude', 'm', {})['identity'] == launch['identity']
helper.set_active('claude', 'b')
child = []
monkeypatch.setattr(helper.os, 'execvpe', lambda executable, argv, env: child.append(env))
monkeypatch.setenv('AI_ACCOUNTS_CLAUDE_OWNER', '1')
helper.main(['exec', 'claude', '--identity', launch['identity'], '--', 'real-harness'])
assert child[0]['CLAUDE_CODE_OAUTH_TOKEN'] == 'synthetic-secret-a'
assert child[0]['AI_ACCOUNTS_CLAUDE_IDENTITY'] == launch['identity']
assert exec_envs[0]['CLAUDE_CODE_OAUTH_TOKEN'] == 'synthetic-secret-a'
assert exec_envs[0]['AI_ACCOUNTS_CLAUDE_IDENTITY'] == launch['identity']


def test_pin_revision_changed_or_explicit_credentials_fails_closed(helper, monkeypatch, capsys):
def test_pin_revision_changed_or_explicit_credentials_fails_closed(helper, monkeypatch, capsys, exec_envs):
revision = helper.with_accounts('claude', {})['AI_ACCOUNTS_CLAUDE_IDENTITY']
children = []
monkeypatch.setattr(helper.os, 'execvpe', lambda *args: children.append(args))
monkeypatch.setenv('CLAUDE_CODE_OAUTH_TOKEN', 'caller-explicit')
assert helper.main(['exec', 'claude', '--identity', revision, '--', 'real-harness']) == 2
assert json.loads(capsys.readouterr().out)['outcome'] == 'unmanaged'
monkeypatch.delenv('CLAUDE_CODE_OAUTH_TOKEN')
helper.write_private(helper.STATE / 'claude/tokens/a', 'synthetic-revised-secret')
assert helper.main(['exec', 'claude', '--identity', revision, '--', 'real-harness']) == 2
assert json.loads(capsys.readouterr().out)['outcome'] == 'unmanaged'
assert children == []
assert exec_envs == []


def test_launch_keeps_unknown_model_unknown(helper, monkeypatch):
Expand Down Expand Up @@ -211,7 +214,7 @@ def test_partial_or_unidentified_codex_auth_keeps_strict_revision(helper, creden
('7d', 1, 1201, 'ok', True, True), ('7d', 1, 0, 'missing', True, True)])
@pytest.mark.parametrize('schema', ['legacy', 'windows'])
@pytest.mark.parametrize('pinned', [False, True])
def test_exec_reserve_policy(helper, monkeypatch, capsys, window, used, age, cache, owner, allowed, pinned, schema):
def test_exec_reserve_policy(helper, monkeypatch, capsys, exec_envs, window, used, age, cache, owner, allowed, pinned, schema):
monkeypatch.delenv('AI_ACCOUNTS_CLAUDE_OWNER', raising=False)
if owner:
monkeypatch.setenv('AI_ACCOUNTS_CLAUDE_OWNER', '1')
Expand All @@ -224,56 +227,46 @@ def test_exec_reserve_policy(helper, monkeypatch, capsys, window, used, age, cac
status['providers']['claude']['accounts'] = {}
if cache != 'missing':
helper.write_private(helper.STATE / 'status.json', '{' if cache == 'broken' else json.dumps(status))
children = []
monkeypatch.setattr(helper.os, 'execvpe', lambda *args: children.append(args))
monkeypatch.setattr(helper, 'probe_claude_model', lambda *args: pytest.fail('exec must not probe'))
args = ['exec', 'claude']
if pinned:
args += ['--identity', helper.identity('claude', 'a')]
code = helper.main([*args, '--', 'fake-cli'])
assert code == (127 if allowed else 3)
assert bool(children) is allowed
assert bool(exec_envs) is allowed
stderr = capsys.readouterr().err
if not allowed:
assert 'account a' in stderr
if used == .85:
assert window in stderr and '85%' in stderr and helper.iso(2000) in stderr


def test_exec_binds_approved_selection_and_preserves_explicit_auth(helper, monkeypatch):
def test_exec_binds_approved_selection_and_preserves_explicit_auth(helper, monkeypatch, exec_envs):
monkeypatch.setenv('AI_ACCOUNTS_CLAUDE_OWNER', '1')
original = helper.with_accounts
def rotate(providers, base, selected=None):
helper.set_active('claude', 'b')
return original(providers, base, selected)
monkeypatch.setattr(helper, 'with_accounts', rotate)
children = []
monkeypatch.setattr(helper.os, 'execvpe', lambda command, args, env: children.append(env))
assert helper.cmd_exec('claude', ['fake']) == 127
assert children[-1]['CLAUDE_CODE_OAUTH_TOKEN'] == 'synthetic-secret-a'
assert exec_envs[-1]['CLAUDE_CODE_OAUTH_TOKEN'] == 'synthetic-secret-a'
assert original('claude', {}, {'claude': None}) == {}
assert original('claude', {'ANTHROPIC_API_KEY': 'explicit'}, {'claude': 'a'}) == {'ANTHROPIC_API_KEY': 'explicit'}


def test_exec_prefers_account_under_reserve(helper, monkeypatch):
@pytest.mark.parametrize('key', [None, 'ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN'])
def test_exec_selects_under_reserve_or_preserves_caller_auth(helper, monkeypatch, exec_envs, key):
monkeypatch.delenv('AI_ACCOUNTS_CLAUDE_OWNER', raising=False)
accounts = {n: {'models': {'m': {'util': {'7d': used}}}} for n, used in (('a', .9), ('b', .5))}
status = {'checked_at': helper.now(), 'providers': {'claude': {'accounts': accounts}}}
helper.write_private(helper.STATE / 'status.json', json.dumps(status))
children = []
monkeypatch.setattr(helper.os, 'execvpe', lambda command, args, env: children.append(env))
assert helper.cmd_exec('claude', ['fake']) == 127
assert children[0]['CLAUDE_CODE_OAUTH_TOKEN'] == 'synthetic-secret-b'


@pytest.mark.parametrize('key', ['ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN'])
def test_exec_explicit_auth_skips_reserve_guard(helper, monkeypatch, key):
monkeypatch.delenv('AI_ACCOUNTS_CLAUDE_OWNER', raising=False)
monkeypatch.setenv(key, 'caller-owned')
children = []
monkeypatch.setattr(helper.os, 'execvpe', lambda command, args, env: children.append(env))
if key is None:
accounts = {n: {'models': {'m': {'util': {'7d': used}}}} for n, used in (('a', .9), ('b', .5))}
status = {'checked_at': helper.now(), 'providers': {'claude': {'accounts': accounts}}}
helper.write_private(helper.STATE / 'status.json', json.dumps(status))
key, expected = 'CLAUDE_CODE_OAUTH_TOKEN', 'synthetic-secret-b'
else:
expected = 'caller-owned'
monkeypatch.setenv(key, expected)
assert helper.cmd_exec('claude', ['fake']) == 127
assert children[0][key] == 'caller-owned'
assert exec_envs[0][key] == expected


@pytest.mark.parametrize('code,retry_after,delay', [
Expand Down
Loading
Loading