diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index 5f8ebcf5..f4bf6fec 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -61,6 +61,7 @@ import threading import time import urllib.error import urllib.request +from contextlib import contextmanager, nullcontext from pathlib import Path from zoneinfo import ZoneInfo @@ -163,32 +164,50 @@ def shared(entry: Path) -> bool: return entry.name not in CODEX_PRIVATE and not entry.name.endswith(".lock") -def sync_codex_home(home: Path) -> None: - """Keep an extra CODEX_HOME a mirror of ~/.codex except its own auth.json. +class AccountLockTimeout(TimeoutError): + pass - Entries the account created itself move into ~/.codex (unless ~/.codex already has one), - then every shared ~/.codex entry is linked, including ones created after `add`. - """ + +@contextmanager +def _locked(name: str): + with (STATE / name).open("a") as lock: + deadline = time.monotonic() + 60 + while (remaining := deadline - time.monotonic()) > 0: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + time.sleep(min(0.1, remaining)) + else: + raise AccountLockTimeout(f"{name} is busy; retry when the other command finishes") + yield + + +def sync_codex_home(home: Path, *, create: bool = False) -> None: STATE.mkdir(parents=True, exist_ok=True, mode=0o700) - # Own lock (check() holds .lock while calling this); Codex may still create entries - # concurrently, so a lost race on one entry is skipped, not fatal. - with open(STATE / ".codex-sync.lock", "w") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) - for entry in home.iterdir(): - target = CODEX_MAIN / entry.name - if shared(entry) and not entry.is_symlink() and not target.exists() \ - and not target.is_symlink(): - try: - os.rename(entry, target) - except FileNotFoundError: - pass - for src in CODEX_MAIN.iterdir(): - dst = home / src.name - if shared(src) and not dst.exists() and not dst.is_symlink(): - try: - dst.symlink_to(src) - except FileExistsError: - pass + with _locked(".codex-sync.lock"): + if create: + home.mkdir(parents=True, exist_ok=True, mode=0o700) + _sync_codex_home(home) + + +def _sync_codex_home(home: Path) -> None: + """Mirror shared Codex files while holding the home lock.""" + for entry in home.iterdir(): + target = CODEX_MAIN / entry.name + if shared(entry) and not entry.is_symlink() and not target.exists() \ + and not target.is_symlink(): + try: + os.rename(entry, target) + except FileNotFoundError: + pass + for src in CODEX_MAIN.iterdir(): + dst = home / src.name + if shared(src) and not dst.exists() and not dst.is_symlink(): + try: + dst.symlink_to(src) + except FileExistsError: + pass def identity(provider: str, name: str) -> str: @@ -232,14 +251,14 @@ def managed_name(provider: str, env: dict[str, str]) -> str | None: return None -def account_env(provider: str, name: str | None = None) -> dict[str, str]: +def account_env(provider: str, name: str | None = None, *, sync_home: bool = True) -> dict[str, str]: name = active(provider) if name is None else name if name is None: return {} if provider == "claude": env = {"CLAUDE_CODE_OAUTH_TOKEN": claude_token(name)} else: - if name != "main": + if name != "main" and sync_home: sync_codex_home(codex_home(name)) env = {"CODEX_HOME": str(codex_home(name)), "AI_ACCOUNTS_CODEX_HOME": str(codex_home(name))} @@ -250,7 +269,7 @@ def with_accounts(providers: str, base: dict[str, str], selected: dict[str, str | None] | None = None) -> dict[str, str]: """Rebind verified managed inheritance; caller credentials and billing always win.""" env = dict(base) - for provider in providers.split(","): + for provider in dict.fromkeys(providers.split(",")): if provider not in PROVIDERS: continue credential = "CLAUDE_CODE_OAUTH_TOKEN" if provider == "claude" else "CODEX_HOME" @@ -718,8 +737,7 @@ def snapshot_fields(result: dict, instance: str, checked_at: float) -> None: def check(quiet: bool = False) -> dict: STATE.mkdir(parents=True, exist_ok=True, mode=0o700) - with open(STATE / ".lock", "w") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) + with _locked(".lock"): try: previous = json.loads((STATE / "status.json").read_text()) except (OSError, ValueError): @@ -727,11 +745,14 @@ def check(quiet: bool = False) -> dict: status = {"checked_at": now(), "providers": {}, "exhausted": previous.get("exhausted", {}), "selections": previous.get("selections", {})} + codex_names = accounts("codex") + homes = [codex_home(name) for name in codex_names if name != "main"] + if homes: + with _locked(".codex-sync.lock"): + for home in homes: + _sync_codex_home(home) for provider in PROVIDERS: - names = accounts(provider) - if provider == "codex": - for n in names[1:] if names[:1] == ["main"] else names: - sync_codex_home(codex_home(n)) + names = codex_names if provider == "codex" else accounts(provider) probe = check_claude if provider == "claude" else check_codex results = {n: probe(n) for n in names} if provider == "claude": @@ -839,8 +860,7 @@ def cmd_add(provider: str, name: str) -> int: print(f"stored claude account {name}; run `ai-accounts check`") return 0 home = STATE / "codex/homes" / name - home.mkdir(parents=True, exist_ok=True, mode=0o700) - sync_codex_home(home) + sync_codex_home(home, create=True) print(f"created {home} (shares ~/.codex except its own auth.json)") print(f"now log in with the other ChatGPT account: CODEX_HOME={home} codex login") return 0 @@ -853,8 +873,7 @@ def cmd_exec(providers: str, argv: list[str]) -> int: # Caller-owned credentials and billing routes skip managed-account admission. if "claude" in providers.split(",") and not caller_credentials("claude", base): STATE.mkdir(parents=True, exist_ok=True, mode=0o700) - with open(STATE / ".lock", "a") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) + with _locked(".lock"): name = active("claude") # The monitor switches only at the 95% margin; prefer any account under the reserve. if claude_exec_refusal(name) is not None: @@ -900,8 +919,8 @@ def launch(provider: str, model: str, env: dict[str, str]) -> dict: return result("unsupported") if caller_credentials(provider, env) or not STATE.is_dir() or not accounts(provider): return result("unmanaged") - with open(STATE / ".lock", "a") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) + home_lock = _locked(".codex-sync.lock") if provider == "codex" else nullcontext() + with _locked(".lock"), home_lock: try: status = json.loads((STATE / "status.json").read_text()) except (OSError, ValueError): @@ -942,8 +961,7 @@ def cmd_pinned_exec(provider: str, revision: str, argv: list[str]) -> int: env = dict(os.environ) name = None if provider in PROVIDERS and STATE.is_dir() and not caller_credentials(provider, env): - with open(STATE / ".lock", "a") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) + with _locked(".lock"): for candidate in accounts(provider): try: if identity(provider, candidate) == revision: @@ -951,6 +969,8 @@ def cmd_pinned_exec(provider: str, revision: str, argv: list[str]) -> int: if env.get(marker(provider)) == revision: name = candidate break + except AccountLockTimeout: + raise except (OSError, ValueError): continue if name is None or not argv: @@ -963,7 +983,7 @@ def cmd_pinned_exec(provider: str, revision: str, argv: list[str]) -> int: return 127 -def exhausted(provider: str, failed_identity: str, model: str) -> dict: +def exhausted(provider: str, failed_identity: str, model: str, *, retry_env: dict[str, str] | None = None) -> dict: """Compare-and-select for one exact provider/model, serialized with monitor checks. The caller sends only the opaque managed revision from its effective environment. @@ -979,8 +999,14 @@ def exhausted(provider: str, failed_identity: str, model: str) -> dict: return result("unsupported") if not STATE.is_dir(): return result("unmanaged") - with open(STATE / ".lock", "a") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) + def prepare(name: str) -> None: + if retry_env is not None: + if provider == "codex" and name != "main": + _sync_codex_home(codex_home(name)) + retry_env.update(account_env(provider, name, sync_home=False)) + + home_lock = _locked(".codex-sync.lock") if provider == "codex" else nullcontext() + with _locked(".lock"), home_lock: revisions = {} for name in accounts(provider): try: @@ -1018,6 +1044,7 @@ def exhausted(provider: str, failed_identity: str, model: str) -> dict: known = False if usable or not known: if usable: + prepare(current) selected[selection_key] = {"identity": current_id, "until": now() + 300} write_private(STATE / "status.json", json.dumps(status) + "\n") return result("already-switched" if usable else "unknown", current) @@ -1037,6 +1064,7 @@ def exhausted(provider: str, failed_identity: str, model: str) -> dict: unknown = True if candidates: chosen = min(candidates)[1] + prepare(chosen) set_active(provider, chosen) selected[selection_key] = {"identity": identity(provider, chosen), "until": now() + 300} outcome = result("already-switched" if chosen == current else "switched", chosen) @@ -1050,8 +1078,8 @@ def cmd_run(providers: str, argv: list[str], retry_exit: set[int] | None = None, base: dict[str, str] | None = None, model: str | None = None, retry_safe: bool = False) -> int: """Preserve stdout streaming; replay only one identified managed provider/model.""" + env = with_accounts(providers, dict(os.environ) if base is None else base) for attempt in (1, 2): - env = with_accounts(providers, dict(os.environ) if base is None else base) proc = subprocess.Popen(argv, env=env, stderr=subprocess.PIPE) seen: list[bytes] = [] @@ -1073,10 +1101,11 @@ def cmd_run(providers: str, argv: list[str], retry_exit: set[int] | None = None, or not USAGE_LIMIT_RE.search(text) or managed_name(providers, env) is None): return code before = env[marker(providers)] - outcome = exhausted(providers, before, model) - after = with_accounts(providers, env) - if not retry_safe or not outcome["changed"] or after.get(marker(providers)) == before: + after = {} + outcome = exhausted(providers, before, model, retry_env=after if retry_safe else None) + if not outcome["changed"] or not after or after.get(marker(providers)) == before: return code + env.update(after) print("ai-accounts: managed account changed; retrying once", file=sys.stderr) return code @@ -1159,8 +1188,7 @@ def main(argv: list[str]) -> int: if argv[2] not in accounts(argv[1]): sys.exit(f"ai-accounts: unknown {argv[1]} account {argv[2]!r}") STATE.mkdir(parents=True, exist_ok=True, mode=0o700) - with open(STATE / ".lock", "a") as lock: - fcntl.flock(lock, fcntl.LOCK_EX) + with _locked(".lock"): set_active(argv[1], argv[2]) log(f"{argv[1]}: manual -> {argv[2]}") print(f"{argv[1]} active: {argv[2]}") @@ -1202,4 +1230,9 @@ def main(argv: list[str]) -> int: if __name__ == "__main__": shim = Path(sys.argv[0]).name - sys.exit(cmd_shim(shim, sys.argv[1:]) if shim in SHIMS else main(sys.argv[1:])) + try: + code = cmd_shim(shim, sys.argv[1:]) if shim in SHIMS else main(sys.argv[1:]) + except AccountLockTimeout as exc: + print(f"ai-accounts: {exc}", file=sys.stderr) + code = 1 + sys.exit(code) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index e6012622..3a17a4ff 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -37,7 +37,6 @@ RUNNER_FAILURES = (runners.RunnerMissing, runners.RunnerAuthFailed, runners.RunnerBadOutput) HANDLED = (LoopZeroError, worktree.WorktreeError, github.GhError, OSError, ValueError) UNEXPECTED = (KeyError, TypeError) -PAGE = 100 # --wait: poll interval, default timeout, and how long a required check may stay # missing before GitHub is assumed to have dropped the event for this head. # Each poll costs several GitHub API calls from a quota shared by every session. @@ -151,10 +150,7 @@ def _context(args: argparse.Namespace, *, pin_checks: bool = False) -> tuple[Pat def _is_ancestor(wt: Path, sha: str, head: str) -> bool: - done = _proc.run( - ["git", "merge-base", "--is-ancestor", sha, head], - cwd=wt, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT, - ) + done = config_mod.run_git(wt, "merge-base", "--is-ancestor", sha, head) if done.exit_code not in (0, 1): detail = _proc.tail(done.stderr or done.stdout, 1) raise CliError(f"git merge-base --is-ancestor failed (exit {done.exit_code}): " @@ -164,10 +160,7 @@ def _is_ancestor(wt: Path, sha: str, head: str) -> bool: def _primary_base(wt: Path, config: Config) -> str: base = config.trusted_base_revision or config_mod.base_revision(wt, config.base_branch) - done = _proc.run( - ["git", "merge-base", base, "HEAD"], - cwd=wt, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT, - ) + done = config_mod.run_git(wt, "merge-base", base, "HEAD") if done.exit_code == 0: return done.stdout.strip() if done.exit_code != 1: @@ -185,9 +178,7 @@ def _require_clean(wt: Path) -> None: def _require_task_branch(config: Config, branch: str) -> None: if branch == config.base_branch: - raise CliError( - f"branch {branch!r} is the configured base; use a task branch" - ) + raise CliError(f"branch {branch!r} is the configured base; use a task branch") def _require_pr(config: Config, branch: str, *, allow_merged: bool = False) -> github.PR: @@ -213,11 +204,11 @@ def _rest_rows(endpoint: str, what: str) -> list[dict]: """Every row of a REST list, oldest first, following pages until a short one.""" rows: list[dict] = [] for page in range(1, 101): - batch = github.api_get(f"{endpoint}?per_page={PAGE}&page={page}") + batch = github.api_get(f"{endpoint}?per_page={github.PAGE}&page={page}") if not isinstance(batch, list) or not all(isinstance(row, dict) for row in batch): raise CliError(f"invalid GitHub {what} response") rows += batch - if len(batch) < PAGE: + if len(batch) < github.PAGE: return rows raise CliError(f"GitHub {what} pagination limit exceeded") @@ -309,10 +300,7 @@ def _readiness( report = _load_report(wt) receipt_problem = _check_report_problem(report, wt, config, head) if receipt_problem: - result = github.Readiness( - ready=False, - reasons=(*result.reasons, receipt_problem), - ) + result = github.Readiness(False, (*result.reasons, receipt_problem)) elif announce_receipt: _print_receipt(wt, report, "accepted") if config.merge_strategy == "mergify" and pr.state == "OPEN": @@ -536,12 +524,6 @@ def replace(match: re.Match[str]) -> str: return prefix + content.lstrip("\n") -def _update_pr_checks(wt: Path, head: str, config: Config, pr: github.PR) -> None: - 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) - - _REQUIRED_TASK_LINES = ("Context", "Problem", "Goal") @@ -576,24 +558,17 @@ 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: - upstream = _proc.run(argv, cwd=wt, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT) - 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 not None and pr.head_sha == head: - _update_pr_checks(wt, head, config, pr) + with _lock_task_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) except (github.GhError, _proc.ProcTimeout, OSError, ValueError, CliError) as exc: print(f"note: could not refresh PR checks: {_one_line(exc)}", file=sys.stderr) @@ -615,8 +590,7 @@ def _pr_title(wt: Path, branch: str) -> str: def cmd_start(args: argparse.Namespace) -> int: root = _toplevel() - argv = ["git", "symbolic-ref", "--quiet", "--short", "HEAD"] - current = _proc.run(argv, cwd=root, env_allowlist=worktree.GIT_ENV, timeout=GIT_TIMEOUT) + current = config_mod.run_git(root, "symbolic-ref", "--quiet", "--short", "HEAD") if current.stdout.strip().startswith("lz/") or ( current.exit_code == 1 and worktree.is_linked_checkout(root) ): @@ -814,16 +788,12 @@ def cmd_review(args: argparse.Namespace, wt: Path, config: Config) -> int: login.casefold() for login in config.review_publishers }: raise CliError("current GitHub login is not a configured review publisher") - reviews = [] if args.repost else _pr_reviews(config.repo, pr.number) - if args.repost: - saved = [kind for kind in ("primary", "delta") if _review_file(wt, head, kind).exists()] - if len(saved) > 1: - raise CliError("multiple saved reviews for HEAD; publication is ambiguous") - if not saved: - reviews = _pr_reviews(config.repo, pr.number) - kind = saved[0] if saved else _decide_kind( - _pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head - )[0] + saved = [kind for kind in ("primary", "delta") if _review_file(wt, head, kind).exists()] if args.repost else [] + if len(saved) > 1: + raise CliError("multiple saved reviews for HEAD; publication is ambiguous") + reviews = [] if saved else _pr_reviews(config.repo, pr.number) + if saved: + kind = saved[0] else: kind, reviewed = _decide_kind( _pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number), head @@ -1128,7 +1098,6 @@ def select(family: str) -> Callable[..., ReviewResult]: try: try: result = selected[family](diff=diff) - break except runners.RunnerPromptTooLong: chunks = runners.split_diff(diff, config.review_chunk_bytes) print( @@ -1138,7 +1107,7 @@ def select(family: str) -> Callable[..., ReviewResult]: chunk_results = [selected[family](diff=chunk, chunk=(index, len(chunks))) for index, chunk in enumerate(chunks, 1)] result = runners.merge_reviews(chunk_results) - break + break except RUNNER_FAILURES as exc: reason, detail, fallback_reason = _review_failure(family, exc) errors[family] = detail, exc.tail if isinstance(exc, runners.RunnerMalformedOutput) else "" @@ -1384,16 +1353,17 @@ def cmd_ready(args: argparse.Namespace) -> int: return 0 +def _required_check_reasons(names: tuple[str, ...], *states: str) -> dict[str, str]: + return {f"required check '{name}' {state}": name for name in names for state in states} + + def _draft_checks_waiting( config: Config, pr: github.PR, readiness: github.Readiness ) -> tuple[str, ...]: reasons = set(readiness.reasons) - {MERGEABILITY_PENDING} if not pr.is_draft or not reasons: return () - expected: dict[str, str] = {} - for name in config.required_ci: - expected[f"required check '{name}' missing on {pr.head_sha[:12]}"] = name - expected[f"required check '{name}' is skipped"] = name + expected = _required_check_reasons(config.required_ci, f"missing on {pr.head_sha[:12]}", "is skipped") if not reasons <= expected.keys(): return () blocked = {expected[reason] for reason in reasons} @@ -1408,9 +1378,8 @@ def _pending_checks( An explicit ready wait can observe a skipped result left over from draft CI. """ states = [f"missing on {pr.head_sha[:12]}", "is pending", *(["is skipped"] if allow_skipped else [])] - waitable = {f"required check '{n}' {state}" for n in config.required_ci for state in states} - waitable.update(readiness.waitable_failures) - waitable.add(MERGEABILITY_PENDING) + waitable = {*_required_check_reasons(config.required_ci, *states), + *readiness.waitable_failures, MERGEABILITY_PENDING} reasons = readiness.reasons return reasons if reasons and all(r in waitable for r in reasons) else () @@ -1460,10 +1429,11 @@ def _wait_with_deadline( allow_merged: bool = False, allow_skipped: bool = False, initial: github.Readiness | None = None, ) -> tuple[github.PR, github.Readiness | None, bool] | None: started = time.monotonic() if started is None else started + wait = partial(_wait_for_checks, wt, config, pr, timeout, kicked=kicked, started=started, + shown=shown, args=args, allow_merged=allow_merged, + allow_skipped=allow_skipped, initial=initial) if timeout == 0: - return _wait_for_checks(wt, config, pr, timeout, kicked=kicked, started=started, - shown=shown, args=args, allow_merged=allow_merged, - allow_skipped=allow_skipped, initial=initial) + return wait() deadline = started + timeout if time.monotonic() >= deadline: _print_check_wait_timeout(pr, args) @@ -1471,9 +1441,7 @@ def _wait_with_deadline( reported_timeout = False try: with github.bounded_reads(deadline, token=None, retry=True): - waited = _wait_for_checks(wt, config, pr, timeout, kicked=kicked, started=started, - shown=shown, args=args, bounded=True, allow_merged=allow_merged, - allow_skipped=allow_skipped, initial=initial) + waited = wait(bounded=True) reported_timeout = waited is None except github.ReadDeadline: if not reported_timeout: @@ -1722,6 +1690,9 @@ def _wait_for_mergify( return None +_FOLLOW_QUEUE = "next: loopzero merge --wait follows the queue, verifies and cleans up" + + class _AdmissionDeadline(Exception): """The --wait budget expired before a new merge or queue request.""" @@ -1747,7 +1718,6 @@ def _merge_with_mergify( confirmed = state is not None if confirmed and not confirmed_marker: mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue) - confirmed_marker = True if not confirmed and confirmed_marker: closed: list[github.GhError] = [] if sha := _mergify_departure(config, pr, queue, closed, confirmed=True): @@ -1758,14 +1728,10 @@ def _merge_with_mergify( if admit_by is not None and time.monotonic() > admit_by: raise _AdmissionDeadline mergify.request(config.repo, pr.number, pr.head_sha, queue) - requested = True if deadline is not None: return _wait_for_mergify(config, pr, max(0.0, deadline - time.monotonic()), confirmed) state_name = "confirmed in" if confirmed else "requested from" - print( - f"PR #{pr.number} {state_name} Mergify queue {queue}; " - "next: loopzero merge --wait follows the queue, verifies and cleans up" - ) + print(f"PR #{pr.number} {state_name} Mergify queue {queue}; {_FOLLOW_QUEUE}") return None @@ -1797,10 +1763,7 @@ def cmd_merge(args: argparse.Namespace) -> int: return 3 pr, readiness, _ = waited if readiness is None: - sha = github.merged_sha( - config.repo, pr.number, - expected_head=pr.head_sha, - ) + sha = github.merged_sha(config.repo, pr.number, expected_head=pr.head_sha) if sha is None: raise CliError(f"PR #{pr.number} reports MERGED but has no merge commit yet; rerun") print(f"PR #{pr.number} was already merged as {sha[:12]}; cleaning up") @@ -1826,10 +1789,7 @@ def cmd_merge(args: argparse.Namespace) -> int: print(f"timed out waiting for the merge queue to land PR #{pr.number}") return 3 if sha is None: - print( - f"PR #{pr.number} is queued for merge into {config.base_branch}; " - "next: loopzero merge --wait follows the queue, verifies and cleans up" - ) + print(f"PR #{pr.number} is queued for merge into {config.base_branch}; {_FOLLOW_QUEUE}") return 0 _cleanup_remote_refs(wt, config, branch, pr.head_sha) _cleanup(wt, pr) diff --git a/src/loopzero/config.py b/src/loopzero/config.py index 2db069b3..edf87338 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -24,26 +24,14 @@ _SECTIONS: dict[str, dict[str, type]] = { "repo": {"name": str, "base": str}, "checks": { - "commands": list, - "runner": list, - "inputs": dict, - "required_ci": list, - "network": bool, - "env_allowlist": list, - "ro_paths": list, - "writable": list, - "scratch": list, - "env": dict, - "limits": dict, + "commands": list, "runner": list, "inputs": dict, "required_ci": list, "network": bool, + "env_allowlist": list, "ro_paths": list, "writable": list, "scratch": list, + "env": dict, "limits": dict, }, "delivery": { - "merge": str, - "mergify_queue": str, - "reviewers": list, - "review_publishers": list, - "reviewer_ro_paths": list, - "review_chunk_bytes": int, - "review": dict, + "merge": str, "mergify_queue": str, + "reviewers": list, "review_publishers": list, "reviewer_ro_paths": list, + "review_chunk_bytes": int, "review": dict, }, } @@ -75,12 +63,13 @@ def load(path: Path | str) -> Config: raise ConfigError(f"{path}: {exc}") from None +def run_git(worktree: Path, *args: str, timeout: float = 60) -> _proc.Completed: + return _proc.run(["git", *args], cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=timeout) + + def base_revision(worktree: Path, base_branch: str) -> str: """Resolve the remote base, or the task's recorded base when the ref is absent.""" - done = _proc.run( - ["git", "rev-parse", "--verify", "--quiet", f"refs/remotes/origin/{base_branch}"], - cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, - ) + done = run_git(worktree, "rev-parse", "--verify", "--quiet", f"refs/remotes/origin/{base_branch}") if done.exit_code == 0: return done.stdout.strip() if done.exit_code == 1: @@ -152,10 +141,7 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, re def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: bool = False) -> Config: """Select delivery policy using Git's origin default and its trusted workflow.""" prefix = "refs/remotes/origin/" - default = _proc.run( - ["git", "symbolic-ref", "--quiet", f"{prefix}HEAD"], - cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60, - ) + default = run_git(worktree, "symbolic-ref", "--quiet", f"{prefix}HEAD") ref = default.stdout.strip() if default.exit_code != 0 or not ref.startswith(prefix): raise ConfigError( @@ -214,20 +200,20 @@ def _build(data: dict[str, Any]) -> Config: raise ConfigError(f"unknown review family delivery.review.{family}") if not isinstance(table, dict): raise ConfigError(f"[delivery.review.{family}] must be a table") - _reject_unknown( - f"[delivery.review.{family}]", table, ("model", "effort", "allowed_efforts") - ) + 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"delivery.review.{family}.{key} must be a non-empty str") - if "allowed_efforts" in table and not isinstance(table["allowed_efforts"], list): - raise ConfigError(f"delivery.review.{family}.allowed_efforts must be a list") - allowed = _strings( - f"delivery.review.{family}.allowed_efforts", table.get("allowed_efforts", []) - ) - review[family] = ReviewConfig(table.get("model"), table.get("effort"), allowed) - - commands = _commands(checks.get("commands", [])) + 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)) + + 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"]) @@ -244,12 +230,11 @@ def _build(data: dict[str, Any]) -> Config: raise ConfigError(f"{label} must exactly match a checks.commands entry") inputs[key] = _strings(label, value) kwargs["inputs"] = inputs - if "env_allowlist" in checks: - kwargs["env_allowlist"] = _strings("checks.env_allowlist", checks["env_allowlist"]) - if "ro_paths" in checks: - kwargs["sandbox_ro"] = _host_paths("checks.ro_paths", checks["ro_paths"]) - if "writable" in checks: - kwargs["writable"] = _host_paths("checks.writable", checks["writable"]) + for key, field, read in (("env_allowlist", "env_allowlist", _strings), + ("ro_paths", "sandbox_ro", _host_paths), + ("writable", "writable", _host_paths)): + if key in checks: + kwargs[field] = read(f"checks.{key}", checks[key]) if "env" in checks: kwargs["env"] = _env_table(checks["env"]) if "scratch" in checks: @@ -306,13 +291,6 @@ def _reject_unknown(where: str, table: dict[str, Any], allowed: Any) -> None: raise ConfigError(f"unknown key(s) in {where}: {', '.join(unknown)}") -def _commands(value: list[Any]) -> tuple[str, ...]: - commands = _strings("checks.commands", value) - if any(not command.strip() for command in commands): - raise ConfigError("checks.commands entries must each be a nonblank command") - return commands - - def _strings(label: str, value: list[Any]) -> tuple[str, ...]: if not isinstance(value, list) or not all(isinstance(item, str) and item for item in value): raise ConfigError(f"{label} must be a list of non-empty strings") diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index a3133441..e51d80ab 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -491,3 +491,68 @@ def test_status_prints_account_email_after_plan(helper, capsys, provider, email, result = {'tier': 0, 'plan': 'max', 'email': email, 'windows': [], 'unknown_reason': 'no data'} helper.print_status({'checked_at': helper.now(), 'providers': {provider: {'active': 'a', 'accounts': {'a': result}}}}) assert shown in capsys.readouterr().out + + +def test_account_lock_timeout_leaves_files_untouched(helper, monkeypatch): + for name in ("main", "b", "c"): + auth = {"tokens": {"account_id": name, "access_token": "expiring"}} + helper.write_private(helper.codex_home(name) / "auth.json", json.dumps(auth)) + helper.set_active("codex", "main") + status = helper.STATE / "status.json" + cooldown = {"exhausted": {helper.identity("codex", "main") + ":model": helper.now() + 300}} + helper.write_private(status, json.dumps(cooldown)) + for key in (*helper.EXPLICIT_ROUTES["codex"], "CODEX_HOME"): + monkeypatch.delenv(key, raising=False) + elapsed = 0.0 + + def advance(seconds): + nonlocal elapsed + elapsed += seconds + + def premature_probe(*args): + pytest.fail("account probing started before the home lock was acquired") + + monkeypatch.setattr(helper.time, "monotonic", lambda: elapsed) + monkeypatch.setattr(helper.time, "sleep", advance) + monkeypatch.setattr(helper, "check_claude", premature_probe) + monkeypatch.setattr(helper, "codex_in_use", lambda _: False) + monkeypatch.setattr(helper, "refresh_codex", premature_probe) + monkeypatch.setattr(helper, "_http", premature_probe) + with (helper.STATE / ".lock").open("a") as holder: + helper.fcntl.flock(holder, helper.fcntl.LOCK_EX) + with pytest.raises(helper.AccountLockTimeout, match=r"^\.lock is busy"): + helper.check(quiet=True) + with (helper.STATE / ".codex-sync.lock").open("a") as holder: + helper.fcntl.flock(holder, helper.fcntl.LOCK_EX) + operations = ( + lambda: helper.check(quiet=True), + lambda: helper.launch("codex", "model", {}), + lambda: helper.cmd_add("codex", "new"), + lambda: helper.cmd_pinned_exec("codex", helper.identity("codex", "b"), ["unused"]), + lambda: helper.exhausted("codex", helper.identity("codex", "main"), "model", retry_env={}), + ) + for operation in operations: + with pytest.raises(helper.AccountLockTimeout, match=r"\.codex-sync\.lock is busy"): + operation() + assert elapsed == 360 + assert not helper.codex_home("new").exists() + assert helper.active("codex") == "main" + assert helper.active("claude") == "a" + assert json.loads(status.read_text()) == cooldown + + acquire = helper._locked + home_lock_entries = [] + + def count_home_lock(name): + if name == ".codex-sync.lock": + home_lock_entries.append(name) + return acquire(name) + + monkeypatch.setattr(helper, "_locked", count_home_lock) + monkeypatch.setattr(helper, "check_claude", lambda _: {"tier": -1}) + monkeypatch.setattr(helper, "check_codex", lambda _: {"tier": -1}) + helper.check(quiet=True) + assert home_lock_entries == [".codex-sync.lock"] + helper.set_active("codex", "b") + assert helper.with_accounts("codex,codex", {})["CODEX_HOME"] == str(helper.codex_home("b")) + assert home_lock_entries == [".codex-sync.lock"] * 2