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
11 changes: 7 additions & 4 deletions scripts/ai-accounts/ai-accounts
Original file line number Diff line number Diff line change
Expand Up @@ -607,10 +607,13 @@ def refresh_codex(auth_file: Path, auth: dict) -> tuple[str, dict]:
fresh = json.loads(raw)
tokens.update({k: fresh[k] for k in ("id_token", "access_token", "refresh_token") if fresh.get(k)})
auth["last_refresh"] = dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
# Rewrite in place like Codex: reviewers bind-mount this inode, so os.replace would detach them.
with open(auth_file, "r+", encoding="utf-8") as fh:
fh.write(json.dumps(auth, indent=2) + "\n")
fh.truncate()
# Reviewers bind-mount this inode. Pad shorter JSON with whitespace so
# the completed write is readable without a second, interruptible truncate.
payload = (json.dumps(auth, indent=2) + "\n").encode("utf-8")
with auth_file.open("r+b", buffering=0) as fh:
payload = payload.ljust(os.fstat(fh.fileno()).st_size, b" ")
if os.pwrite(fh.fileno(), payload, 0) != len(payload):
raise OSError("incomplete Codex auth write")
log(f"codex: refreshed {auth_file}")
return tokens["access_token"], tokens

Expand Down
35 changes: 14 additions & 21 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,24 +171,20 @@ def api_error_diagnostics():

def _included_response(output: str) -> tuple[str | None, dict[str, str], str]:
"""Split one `gh api --include` response into status, headers and body."""
head, separator, body = output.partition("\r\n\r\n")
line_separator = "\r\n"
if not separator:
head, separator, body = output.partition("\n\n")
line_separator = "\n"
if not separator:
for line_separator in ("\r\n", "\n"):
head, separator, body = output.partition(line_separator * 2)
if separator:
break
else:
return None, {}, output
lines = head.split(line_separator)
match = _HTTP_STATUS_RE.match(lines[0])
if match is None:
return None, {}, output
status = match.group(1)
headers: dict[str, str] = {}
for line in lines[1:]:
name, separator, value = line.partition(":")
if separator:
headers[name.strip().casefold()] = value.strip()
return status, headers, body
headers = {name.strip().casefold(): value.strip()
for name, separator, value in (line.partition(":") for line in lines[1:])
if separator}
return match.group(1), headers, body


def _api_methods(args: tuple[str, ...]) -> list[str]:
Expand Down Expand Up @@ -806,9 +802,8 @@ def _review_body(result: ReviewResult, unplaced: list[Finding], prefix: str = ""
_, span = runners.leading_review_block(prefix)
if len(span.encode("utf-8")) > runners.CODEX_HEADER_LIMIT:
raise runners.RunnerBadOutput("codex: oversized leading machine block; HOLD")
counts = {s: sum(1 for f in result.findings if f.severity == s) for s in
("critical", "important", "suggestion")}
summary = ", ".join(f"{n} {s}" for s, n in counts.items())
severities = [f.severity for f in result.findings]
summary = ", ".join(f"{severities.count(s)} {s}" for s in ("critical", "important", "suggestion"))
duration = "unknown" if result.duration_s is None else f"{result.duration_s:.1f}s"
settings = ""
if settings_layout == "summary":
Expand Down Expand Up @@ -858,11 +853,9 @@ def _review_transcript(result: ReviewResult, legacy_display: bool) -> str:
"Exact raw SHA256: " + hashlib.sha256(result.raw.encode()).hexdigest())
encoded = raw.encode("utf-8")
if len(encoded) > 30_000:
raw = encoded[-30_000:].decode("utf-8", errors="ignore")
raw = (
"[Transcript truncated; showing the last at most 30,000 UTF-8 bytes. "
"Full output remains in the saved local review artifact.]\n" + raw
)
tail = encoded[-30_000:].decode("utf-8", errors="ignore")
raw = ("[Transcript truncated; showing the last at most 30,000 UTF-8 bytes. "
"Full output remains in the saved local review artifact.]\n" + tail)
return f"\n\n<details><summary>Raw reviewer output</summary>\n\n```\n{raw}\n```\n</details>"


Expand Down
74 changes: 28 additions & 46 deletions src/loopzero/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -934,33 +934,23 @@ def _codex_evidence(result):
raise RunnerBadOutput("codex: configured settings/context mismatch")
settings["configured"] = configured
inspection = _native_inspection(envelope, context)
calls.append(
{
"index": index,
"session": session,
**settings,
"fatal": "present" if codex_fatal_startup(envelope) else "absent",
"inspection": "verified" if inspection else "unknown",
**inspection,
"base": context["base"],
"diff_sha256": context["diff_sha256"],
}
)
calls.append({
"index": index, "session": session, **settings,
"fatal": "present" if codex_fatal_startup(envelope) else "absent",
"inspection": "verified" if inspection else "unknown",
**inspection,
"base": context["base"], "diff_sha256": context["diff_sha256"],
})
raw_bytes = result.raw.encode("utf-8")
value = {
"version": 1,
"family": "codex",
"repo": common["repo"],
"pr": common["pr"],
"head": result.head,
"kind": result.kind,
"version": 1, "family": "codex",
"repo": common["repo"], "pr": common["pr"],
"head": result.head, "kind": result.kind,
"publisher": common["publisher"],
"receipt": f".loopzero/review-{result.head[:12]}-{result.kind}.json",
"raw_sha256": hashlib.sha256(raw_bytes).hexdigest(),
"raw_bytes": len(raw_bytes),
"complete": True,
"chunk_count": len(calls),
"calls": calls,
"raw_bytes": len(raw_bytes), "complete": True,
"chunk_count": len(calls), "calls": calls,
}
if not valid_codex_evidence(value):
raise RunnerBadOutput("codex: invalid full native evidence")
Expand All @@ -974,6 +964,7 @@ def codex_evidence(result):
raise RunnerBadOutput("codex: invalid complete native result")
return _codex_evidence(result)


def _codex_rollout_settings(home: Path, session_id: str) -> dict:
"""Read only unambiguous native settings for this private session."""
unknown = {"model": None, "effort": None}
Expand All @@ -999,7 +990,7 @@ def _codex_rollout_settings(home: Path, session_id: str) -> dict:
contexts = [record.get("payload") for record in records if record.get("type") == "turn_context"]
if not contexts or any(not isinstance(context, dict) for context in contexts):
return unknown
claims = [{key: _setting(context.get(key)) for key in unknown} for context in contexts]
claims = [_settings(context) for context in contexts]
return claims[0] if all(claims[0].values()) and all(claim == claims[0] for claim in claims) else unknown
except (OSError, ValueError, TypeError):
return unknown
Expand All @@ -1020,10 +1011,8 @@ def _codex_provenance(
),
None,
)
usage = next(
(event["usage"] for event in reversed(events) if isinstance(event.get("usage"), dict)),
None,
)
usage = next((event["usage"] for event in reversed(events)
if isinstance(event.get("usage"), dict)), None)
session_match = re.search(
r"(?:session|thread)(?:\s+id)?\s*[:=]\s*([A-Za-z0-9_-]{6,})", stderr,
re.IGNORECASE,
Expand All @@ -1033,11 +1022,8 @@ def _codex_provenance(
re.IGNORECASE,
)
session_id = session_id or (session_match.group(1) if session_match else None)
usage = usage or (
{"total_tokens": int(tokens_match.group(1).replace(",", ""))}
if tokens_match
else None
)
usage = usage or ({"total_tokens": int(tokens_match.group(1).replace(",", ""))}
if tokens_match else None)
if not session_id or not isinstance(usage, dict):
raise RunnerBadOutput(
"codex: execution output lacks session/token provenance", _tail(stdout + stderr)
Expand Down Expand Up @@ -1263,15 +1249,20 @@ def review_with(
)


def _review_outcome(results: list[ReviewResult]) -> tuple[tuple[Finding, ...], str]:
findings = tuple(finding for result in results for finding in result.findings)
verdict = "request_changes" if any(r.verdict == "request_changes" for r in results) else "approve"
return findings, verdict


def merge_reviews(results: list[ReviewResult]) -> ReviewResult:
"""Merge same-family chunk reviews while retaining every provider envelope/session."""
if not results:
raise ValueError("cannot merge no reviews")
first = results[0]
if any((r.family, r.head, r.kind) != (first.family, first.head, first.kind) for r in results):
raise ValueError("chunk reviews do not describe the same review")
findings = tuple(finding for result in results for finding in result.findings)
verdict = "request_changes" if any(r.verdict == "request_changes" for r in results) else "approve"
findings, verdict = _review_outcome(results)
envelopes = [json.loads(result.raw) for result in results]
if any(codex_fatal_startup(envelope) for envelope in envelopes):
raise RunnerBadOutput("codex: fatal Code Mode startup failure")
Expand All @@ -1292,10 +1283,7 @@ def merge_reviews(results: list[ReviewResult]) -> ReviewResult:
provenance["token_usage"] = [result.provenance["token_usage"] for result in results]
provenance["cli_versions"] = [result.provenance.get("cli_version") for result in results]
return replace(
first,
fallback="",
verdict=verdict,
findings=findings,
first, fallback="", verdict=verdict, findings=findings,
raw=json.dumps(envelopes, separators=(",", ":")),
model=", ".join(dict.fromkeys(r.model for r in results if r.model)) or None,
effort=", ".join(dict.fromkeys(r.effort for r in results if r.effort)) or None,
Expand Down Expand Up @@ -1434,18 +1422,12 @@ def validate_runner_result(result: ReviewResult) -> bool:
return False
try:
parsed = [
parse_review(
payload, family=result.family, head=result.head, kind=result.kind, raw=result.raw
)
parse_review(payload, family=result.family, head=result.head, kind=result.kind, raw=result.raw)
for payload in payloads
]
except RunnerBadOutput:
return False
findings = tuple(finding for item in parsed for finding in item.findings)
verdict = "request_changes" if any(
item.verdict == "request_changes" for item in parsed
) else "approve"
if result.findings != findings or result.verdict != verdict:
if (result.findings, result.verdict) != _review_outcome(parsed):
return False
try:
if result.family == "codex":
Expand Down
11 changes: 10 additions & 1 deletion src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import re
import stat
import subprocess
import time
from collections.abc import Iterator
from collections.abc import Callable
from contextlib import contextmanager, suppress
Expand Down Expand Up @@ -112,7 +113,15 @@ def _local_state_directory(wt: Path, *, create: bool = False, lock: bool = False
raise WorktreeError(f"local state directory is not a directory or is a symbolic link: {path}") from exc
try:
if lock:
fcntl.flock(fd, fcntl.LOCK_EX)
deadline = time.monotonic() + 60
while (remaining := deadline - time.monotonic()) > 0:
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except BlockingIOError:
time.sleep(min(0.1, remaining))
else:
raise TimeoutError(f"task state is busy in {wt}; retry when the other command finishes")
yield fd
finally:
os.close(fd)
Expand Down
18 changes: 16 additions & 2 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,11 +183,25 @@ def test_codex_select_reserves_current_at_85_without_churn(helper):
def test_codex_refresh_keeps_managed_binding_and_exhaustion_selection(helper, monkeypatch):
auth = helper.CODEX_MAIN / 'auth.json'
principal = {'account_id': 'account-a', 'id_token': 'e30.eyJzdWIiOiJ1c2VyLWEiLCJpc3MiOiJpc3N1ZXIifQ.x'}
helper.write_private(auth, json.dumps({'tokens': {**principal, 'access_token': 'old'}}))
helper.write_private(auth, json.dumps({'tokens': {**principal, 'access_token': 'old' * 100, 'refresh_token': 'old-refresh'}}))
helper.write_private(helper.STATE / 'codex/homes/b/auth.json', json.dumps({'tokens': {'account_id': 'account-b', 'access_token': 'other'}}))
helper.set_active('codex', 'main')
inherited = helper.with_accounts('codex', {})
helper.write_private(auth, json.dumps({'tokens': {**principal, 'access_token': 'fresh', 'refresh_token': 'rotated'}}))
refreshed = {"access_token": "fresh", "refresh_token": "rotated"}
monkeypatch.setattr(helper, "_http", lambda _: (200, {}, json.dumps(refreshed)))
write = helper.os.pwrite

def interrupt(fd, data, offset):
write(fd, data, offset)
raise KeyboardInterrupt

with auth.open("rb") as pinned, monkeypatch.context() as patch:
patch.setattr(helper.os, "pwrite", interrupt)
patch.setattr(helper, "jwt_claims", lambda _: {"client_id": "test"})
with pytest.raises(KeyboardInterrupt):
helper.refresh_codex(auth, json.loads(auth.read_text()))
assert json.load(pinned)["tokens"] == {**principal, **refreshed}
assert auth.stat().st_ino == helper.os.fstat(pinned.fileno()).st_ino
revision = inherited['AI_ACCOUNTS_CODEX_IDENTITY']
assert helper.managed_name('codex', inherited) == 'main'
monkeypatch.setattr(helper, 'check_codex', lambda name: {'tier': 2, 'util': 0, 'models': {'m': True}})
Expand Down
19 changes: 19 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4719,6 +4719,25 @@ def test_wait_rechecks_closed_unmerged_pr(monkeypatch, final) -> None:
assert _closed_unmerged_wait(monkeypatch, reads, steps=1) == final


def test_task_state_lock_times_out_with_a_live_holder(git_repo, monkeypatch):
now = 0.0

def advance(seconds):
nonlocal now
now += seconds

monkeypatch.setattr(cli.worktree, "time", SimpleNamespace(monotonic=lambda: now, sleep=advance))
with cli.worktree.lock_local_state(git_repo):
with (
pytest.raises(TimeoutError, match=r"task state is busy.*retry"),
cli.worktree.lock_local_state(git_repo),
):
pytest.fail("contender acquired a held directory lock")
assert now == 60
with cli.worktree.lock_local_state(git_repo):
assert now == 60


@pytest.mark.parametrize("redirected", [False, True])
def test_checks_report_survives_failed_publication(git_repo, tmp_path, monkeypatch, redirected):
path = git_repo / cli.CHECKS_FILE
Expand Down
8 changes: 8 additions & 0 deletions tests/test_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,14 @@ def test_post_review_payload(gh: FakeGh, raw: str, prefix: str, family: str) ->
assert all("subject_type" not in c for c in comments)


def test_legacy_transcript_truncates_on_utf8_boundary():
tail = "x" * 29_999
result = ReviewResult("claude", HEAD, "primary", "approve", (), "🧪" + tail)
output = github._review_transcript(result, legacy_display=True)
assert "Transcript truncated" in output
assert output.endswith(f"\n{tail}\n```\n</details>")


@pytest.mark.parametrize("metadata", ["new", "legacy", "malformed"])
def test_publication_qualifies_each_call_from_native_evidence(gh, metadata):
arm_review(gh)
Expand Down
Loading