From d91efd7ca51ad1d9d3e79ef25a5fa72548a08f64 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:12:50 +0100 Subject: [PATCH 1/4] Append task excludes without overwriting concurrent edits Architecture-Review: unchanged; start still installs the same repository-local Git ignore rules before adding a task checkout. Co-Authored-By: Codex --- src/loopzero/worktree.py | 37 +++++++++++++++++++------------------ tests/test_worktree.py | 22 +++++++++++++++++----- 2 files changed, 36 insertions(+), 23 deletions(-) diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 7bf653e3..0ad509e2 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -3,17 +3,17 @@ from __future__ import annotations import errno +import fcntl +import os import re -import stat import tempfile from pathlib import Path -from uuid import uuid4 from loopzero._proc import run GIT_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GIT_SSH_COMMAND", "SSH_AUTH_SOCK") _ABSOLUTE_COMMON_DIR = ("rev-parse", "--path-format=absolute", "--git-common-dir") -EXCLUDES = (".worktrees/", ".loopzero/") +EXCLUDES = (b".worktrees/", b".loopzero/") _BASE_LINE = re.compile(r"^Base:\s*([0-9a-fA-F]{7,40})\s*$", re.MULTILINE) _TASK_TEMPLATE = """# {title} @@ -105,21 +105,22 @@ def _ensure_excludes(repo_root: Path) -> None: exclude = common / "info" / "exclude" exclude.parent.mkdir(parents=True, exist_ok=True) exclude = exclude.resolve() - existing = exclude.read_text() if exclude.exists() else "" - missing = [entry for entry in EXCLUDES if entry not in existing.splitlines()] - if missing: - sep = "" if not existing or existing.endswith("\n") else "\n" - mode = stat.S_IMODE(exclude.stat().st_mode) if exclude.exists() else None - temp = exclude.with_name(f".exclude-{uuid4().hex}") - stream = temp.open("x") - try: - with stream: - stream.write(existing + sep + "\n".join(missing) + "\n") - if mode is not None: - temp.chmod(mode) - temp.replace(exclude) - finally: - temp.unlink(missing_ok=True) + while True: + fd = os.open(exclude, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW, 0o666) + with os.fdopen(fd, "rb") as stream: + fcntl.flock(fd, fcntl.LOCK_EX) + lines = set(stream.read().splitlines()) + missing = [entry for entry in EXCLUDES if entry not in lines] + if missing: + # An editor can append an unterminated line before this write. + rules = b"\n" + b"\n".join(missing) + b"\n" + if os.write(fd, rules) != len(rules): + raise WorktreeError(f"incomplete write to Git exclude: {exclude}") + try: + if os.path.samestat(os.fstat(fd), exclude.lstat()): + return + except FileNotFoundError: + pass def start(repo_root: Path, slug: str, base_branch: str) -> Path: diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 230adc02..3002e0d8 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -131,15 +131,27 @@ def interrupt_after_add(cwd, *args, **kwargs): assert task.read_text().endswith("(filled by `loopzero review`)\n") -def test_start_excludes_worktrees_and_task_dir(repo: Path) -> None: +@pytest.mark.parametrize("replacement", [False, True], ids=["append", "replace"]) +def test_start_excludes_worktrees_and_task_dir(repo: Path, monkeypatch, replacement) -> None: exclude = repo / ".git" / "info" / "exclude" - exclude.parent.mkdir(parents=True, exist_ok=True) exclude.write_text("*.log") # no trailing newline on purpose old_inode = exclude.stat().st_ino + write = worktree.os.write + + def interleave(fd, rules): + if rules.endswith(b".loopzero/\n"): + edit = exclude.with_suffix(".edited") if replacement else exclude + with edit.open("w" if replacement else "a") as stream: + stream.write("*.log\nlocal.env" if replacement else "\nlocal.env") + if replacement: + edit.replace(exclude) + monkeypatch.setattr(worktree.os, "write", write) + return write(fd, rules) + + monkeypatch.setattr(worktree.os, "write", interleave) wt = worktree.start(repo, "t1", "main") - assert exclude.stat().st_ino != old_inode - lines = exclude.read_text().splitlines() - assert lines == ["*.log", ".worktrees/", ".loopzero/"] + assert (exclude.stat().st_ino != old_inode) == replacement + assert exclude.read_text().splitlines() == ["*.log", "local.env", ".worktrees/", ".loopzero/"] assert not worktree.is_dirty(wt), "fresh worktree with task.md is clean" assert git(repo, "status", "--porcelain") == "" installed = exclude.stat() From ed981cc5efca431531c849c419c322415030b855 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:54:00 +0100 Subject: [PATCH 2/4] Keep known model availability in partial Codex usage responses Architecture-Review: unchanged; the parser distinguishes unknown entries while retaining the existing exact-model policy. Co-Authored-By: Codex --- scripts/ai-accounts/ai-accounts | 12 +++++++----- tests/test_ai_accounts.py | 3 ++- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index 75828558..9caa2bfc 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -629,13 +629,15 @@ def check_codex(name: str) -> dict: model_usage = data.get("model_usage") if not isinstance(model_usage, dict) or not model_usage: return {**result, "error": "usage response has no model usage"} - if any(not isinstance(v, dict) or not isinstance(v.get("available"), bool) - for v in model_usage.values()): - return {**result, "error": "usage response has incomplete model usage"} - models = {m: v["available"] for m, v in model_usage.items()} + # Entries without a bool `available` are unknown, not a logged-out account: skip them and + # take the tier from the entries that do report availability (response shape drifts). + models = {m: v["available"] for m, v in model_usage.items() + if isinstance(v, dict) and isinstance(v.get("available"), bool)} + unknown = sorted(m for m in model_usage if m not in models) usable = [available for available in models.values() if available] tier = 0 if not ok or (models and not usable) else (2 if all(models.values()) else 1) - return {**result, "tier": tier, "models": models} + extra = {"models_unknown": unknown} if unknown else {} + return {**result, "tier": tier, "models": models, **extra} def select(provider: str, results: dict[str, dict], current: str | None) -> str | None: diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index 9db4ab49..0c53c6f3 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -397,9 +397,10 @@ def test_codex_json_and_text_share_each_existing_window(helper, monkeypatch, cap return week = {'used_percent': 96, 'limit_window_seconds': 604800, 'reset_at': 1794384770} short = {'used_percent': 99, 'limit_window_seconds': 18000, 'reset_at': short_reset} if short_reset else None - data = {'rate_limit': {'primary_window': short or week, 'secondary_window': week if short else None}, 'model_usage': {'m': {'available': True}}} + data = {'rate_limit': {'primary_window': short or week, 'secondary_window': week if short else None}, 'model_usage': {'m': {'available': True}, 'partial': {}}} monkeypatch.setattr(helper, '_http', lambda req: (200, {}, json.dumps(data).encode())) result = helper.check_codex('c2') + assert result['models'] == {'m': True} and result['models_unknown'] == ['partial'] assert result['next_reset'] == 1794384770 status = {'checked_at': 10000, 'providers': {'codex': {'active': 'c2', 'accounts': {'c2': result}}}} helper.write_private(helper.STATE / 'status.json', json.dumps(status)) From 3e974d8358c336b12e1ffec29c6e391301567bc4 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:42:21 +0100 Subject: [PATCH 3/4] Keep malformed Mergify authorization out of diagnostics Architecture-Review: unchanged; only malformed request diagnostics change. Co-Authored-By: Codex --- src/loopzero/mergify.py | 6 +++++- tests/test_mergify.py | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index 61665b00..6b7419d7 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -73,7 +73,11 @@ def redirect_request(self, *_args, **_kwargs): def _open(request: urllib.request.Request): - return urllib.request.build_opener(_NoRedirect).open(request, timeout=30) + try: + return urllib.request.build_opener(_NoRedirect).open(request, timeout=30) + except ValueError: + # The HTTP client can include the Authorization value in a header error. + raise MergifyError("Mergify API request has an invalid URL or header") from None def api_get(repo: str, suffix: str) -> object | None: diff --git a/tests/test_mergify.py b/tests/test_mergify.py index ff3b70e0..88ce09f8 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -1,10 +1,12 @@ from __future__ import annotations import base64 +import http.client import io import json import subprocess import sys +import traceback import urllib.error import urllib.request @@ -17,6 +19,26 @@ def response(payload: object) -> io.BytesIO: return io.BytesIO(json.dumps(payload).encode()) + +@pytest.mark.parametrize(("operation", "args"), [ + (mergify.api_get, ("acme/widgets", "/merge-queue/status")), + (mergify.dequeue, ("acme/widgets", 7)), +]) +def test_malformed_authorization_is_not_logged(monkeypatch, operation, args): + fake_key = "synthetic-mergify-key" + monkeypatch.setenv("MERGIFY_API_KEY", fake_key + "\nsecond-line") + monkeypatch.setattr(urllib.request, "getproxies", dict) + monkeypatch.setattr(mergify, "_retry_sleep", lambda _delay: None) + + def reject_network(_connection): + pytest.fail("invalid Authorization header reached the network") + + monkeypatch.setattr(http.client.HTTPSConnection, "connect", reject_network) + with pytest.raises(mergify.MergifyError, match="invalid URL or header") as failure: + operation(*args) + assert fake_key not in "".join(traceback.format_exception(failure.value)) + + def test_membership_uses_bearer_and_validates_queue(monkeypatch): monkeypatch.setenv("MERGIFY_API_KEY", "secret") seen = [] From a45739690d2279f09f3346dbcf49c1cace6743c2 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:56:03 +0100 Subject: [PATCH 4/4] Keep all-unknown Codex usage in the unknown tier Co-Authored-By: Codex --- scripts/ai-accounts/ai-accounts | 4 +++- tests/test_ai_accounts.py | 12 +++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index 9caa2bfc..c7aeaca2 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -634,8 +634,10 @@ def check_codex(name: str) -> dict: models = {m: v["available"] for m, v in model_usage.items() if isinstance(v, dict) and isinstance(v.get("available"), bool)} unknown = sorted(m for m in model_usage if m not in models) + if not models: + return {**result, "error": "usage response has no known model availability", "models_unknown": unknown} usable = [available for available in models.values() if available] - tier = 0 if not ok or (models and not usable) else (2 if all(models.values()) else 1) + tier = 0 if not ok or not usable else (2 if all(models.values()) else 1) extra = {"models_unknown": unknown} if unknown else {} return {**result, "tier": tier, "models": models, **extra} diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index 0c53c6f3..2d3037a6 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -384,7 +384,7 @@ def http(req): assert ('fallback' in output and 'HTTP 403' in output) is (api == 403) -@pytest.mark.parametrize('short_reset', [None, 1793912400, 'offline']) +@pytest.mark.parametrize('short_reset', [None, 1793912400, 'offline', 'all-unknown']) def test_codex_json_and_text_share_each_existing_window(helper, monkeypatch, capsys, short_reset): helper.write_private(helper.codex_home('c2') / 'auth.json', '{"tokens":{"access_token":"fake"}}') monkeypatch.setattr(helper, 'now', lambda: 10000) @@ -396,11 +396,17 @@ def test_codex_json_and_text_share_each_existing_window(helper, monkeypatch, cap assert 'unknown (network: offline)' in capsys.readouterr().out return week = {'used_percent': 96, 'limit_window_seconds': 604800, 'reset_at': 1794384770} - short = {'used_percent': 99, 'limit_window_seconds': 18000, 'reset_at': short_reset} if short_reset else None + short = {'used_percent': 99, 'limit_window_seconds': 18000, 'reset_at': short_reset} if isinstance(short_reset, int) else None data = {'rate_limit': {'primary_window': short or week, 'secondary_window': week if short else None}, 'model_usage': {'m': {'available': True}, 'partial': {}}} + if short_reset == 'all-unknown': + del data['model_usage']['m'] monkeypatch.setattr(helper, '_http', lambda req: (200, {}, json.dumps(data).encode())) result = helper.check_codex('c2') - assert result['models'] == {'m': True} and result['models_unknown'] == ['partial'] + assert result['models_unknown'] == ['partial'] + if short_reset == 'all-unknown': + assert result['tier'] == -1 and result['error'] == 'usage response has no known model availability' + return + assert result['models'] == {'m': True} assert result['next_reset'] == 1794384770 status = {'checked_at': 10000, 'providers': {'codex': {'active': 'c2', 'accounts': {'c2': result}}}} helper.write_private(helper.STATE / 'status.json', json.dumps(status))