graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(codex): one credential path for #402, and recovery that also covers subagents
Rach Pradhand22b3f906aba
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 52a6b727..6935c46e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -136,6 +136,9 @@ jobs:- name: Newer-issue E2E — blank sessions not persisted (#184)run: python3 scripts/test-e2e-newer-issues.py zig-out/bin/graff+ - name: Expired codex token recovered mid-turn, retry carries it (#402)+ run: python3 scripts/test-codex-auth-recovery.py zig-out/bin/graff+- name: SDK generation driftrun: |python3 sdk/generate.py --harness ./zig-out/bin/graffdiff --git a/scripts/codex_ws_mock.py b/scripts/codex_ws_mock.pyindex da3610ce..0b97a6d8 100644--- a/scripts/codex_ws_mock.py+++ b/scripts/codex_ws_mock.py@@ -96,12 +96,15 @@ class RecordedRequest:``connection_id`` is populated for WebSocket requests so tests can prove apost-compaction request re-anchored on a new socket. SSE requests use None.+ ``headers`` are the request's HTTP headers, lowercased — the credential a+ given attempt actually put on the wire is only observable there (#402)."""ordinal: inttransport: strconnection_id: int | Nonebody: dict+ headers: dict[str, str] = field(default_factory=dict)class _SockReader:@@ -216,6 +219,13 @@ class CodexMock:events_for_request: Callable[[RecordedRequest], list[dict]] | None = field(default=None, repr=False)+ # Optional raw-HTTP escape hatch for the SSE path: return the exact bytes to+ # send (status line + headers + body) instead of a 200 event stream, or None+ # to fall through to ``events_for_request``. Needed for the non-2xx JSON+ # envelopes graff parses itself — e.g. the 401 that #402 recovers from.+ raw_for_request: Callable[[RecordedRequest], bytes | None] | None = field(+ default=None, repr=False+ )requests: list[RecordedRequest] = field(default_factory=list, repr=False)_sock: socket.socket | None = field(default=None, repr=False)_threads: list[threading.Thread] = field(default_factory=list, repr=False)@@ -257,21 +267,38 @@ class CodexMock:if self.verbose:print(f"[codex-mock] {message}", file=sys.stderr, flush=True)- def _events(- self, transport: str, connection_id: int | None, body: dict- ) -> list[dict]:+ def _record(+ self,+ transport: str,+ connection_id: int | None,+ body: dict,+ headers: dict[str, str],+ ) -> RecordedRequest:with self._lock:request = RecordedRequest(ordinal=len(self.requests) + 1,transport=transport,connection_id=connection_id,body=body,+ headers=dict(headers),)self.requests.append(request)+ return request++ def _events_for(self, request: RecordedRequest) -> list[dict]:if self.events_for_request is not None:return self.events_for_request(request)return turn_events(f"resp_mock_{request.ordinal}")+ def _events(+ self,+ transport: str,+ connection_id: int | None,+ body: dict,+ headers: dict[str, str] | None = None,+ ) -> list[dict]:+ return self._events_for(self._record(transport, connection_id, body, headers or {}))+def _accept_loop(self) -> None:srv = self._sockassert srv is not None@@ -358,7 +385,7 @@ class CodexMock:self._log(f"ws <- {etype} ({len(message.payload)}b)")if etype != "response.create":continue- for ev in self._events("ws", connection_id, event):+ for ev in self._events("ws", connection_id, event, headers):_send_frame(conn, OP_TEXT, json.dumps(ev, separators=(",", ":")).encode("utf-8"))@@ -378,7 +405,16 @@ class CodexMock:parsed = {}if not isinstance(parsed, dict):parsed = {}- events = self._events("sse", None, parsed)+ request = self._record("sse", None, parsed, headers)+ if self.raw_for_request is not None:+ raw = self.raw_for_request(request)+ if raw is not None:+ conn.sendall(raw)+ self._log(f"sse -> raw ({len(raw)}b)")+ with self._lock:+ self.sse_turns += 1+ return+ events = self._events_for(request)payload = "".join(f"data: {json.dumps(ev, separators=(',', ':'))}\n\n" for ev in events).encode("utf-8")diff --git a/scripts/test-codex-auth-recovery.py b/scripts/test-codex-auth-recovery.pynew file mode 100644index 00000000..91fc7688--- /dev/null+++ b/scripts/test-codex-auth-recovery.py@@ -0,0 +1,191 @@+#!/usr/bin/env python3+"""#402 end-to-end: an expired ChatGPT token is recovered mid-turn, and the+RETRIED request carries the new bearer.++Driven through a real graff process on a PTY, against the codex mock:++ 1. ``$CODEX_HOME/auth.json`` holds an expired access token; the session starts+ on it, and every request carries it as ``Authorization: Bearer …``.+ 2. Request 1 gets the ChatGPT backend's 401 body verbatim. While serving it,+ the mock rewrites ``$CODEX_HOME/auth.json`` — standing in for the ``/login``+ (or a second graff, or the real ``codex`` CLI) that re-authenticates while+ this session is live.+ 3. graff must adopt that credential without a restart and resend the turn.++Asserted on the wire: a second request exists, it carries the NEW bearer and the+new chatgpt-account-id, and the session prints the reply. Before #402 the turn+died on the 401 body and every later turn re-fired the same expired token, which+is exactly what the issue reports.++$CODEX_HOME deliberately is NOT ``$HOME/.codex``: the credential the recovery+reads has to be the one the login flows write, and this scenario only passes when+both resolve to the same file.+"""++from __future__ import annotations++import json+import os+import sys+import tempfile++from codex_ws_mock import CodexMock, RecordedRequest+from pty_harness import PtySession++_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg++FINAL_REPLY = "AUTH_RECOVERY_OK"+EXPIRED_TOKEN = "tok-expired-402"+FRESH_TOKEN = "tok-fresh-402"+EXPIRED_ACCOUNT = "acct-402"+EXPIRED_BODY = json.dumps(+ {+ "error": {+ "message": "Provided authentication token is expired. Please re-authenticate.",+ "type": "unauthorized",+ }+ }+).encode("utf-8")+++def write_auth(codex_home: str, token: str) -> None:+ with open(os.path.join(codex_home, "auth.json"), "w", encoding="utf-8") as fh:+ json.dump(+ {+ "auth_mode": "chatgpt",+ "tokens": {+ "access_token": token,+ "refresh_token": "", # no grant to spend: STEP 1 adoption only, no network+ "account_id": EXPIRED_ACCOUNT,+ },+ },+ fh,+ )+++def unauthorized() -> bytes:+ return (+ b"HTTP/1.1 401 Unauthorized\r\n"+ b"Content-Type: application/json\r\n"+ b"Content-Length: " + str(len(EXPIRED_BODY)).encode("ascii") + b"\r\n"+ b"Connection: close\r\n\r\n" + EXPIRED_BODY+ )+++def main() -> None:+ with tempfile.TemporaryDirectory(prefix="graff-codex-auth-") as tmp:+ codex_home = os.path.join(tmp, "codex-home")+ os.makedirs(codex_home)+ write_auth(codex_home, EXPIRED_TOKEN)++ def raw(request: RecordedRequest) -> bytes | None:+ if request.ordinal != 1:+ return None+ # The user re-authenticates while the turn is in flight. graff has to+ # notice without being restarted.+ write_auth(codex_home, FRESH_TOKEN)+ return unauthorized()++ def events(request: RecordedRequest) -> list[dict]:+ return [+ {+ "type": "response.output_item.done",+ "item": {+ "type": "message",+ "id": "msg_auth_ok",+ "status": "completed",+ "role": "assistant",+ "content": [+ {"type": "output_text", "text": FINAL_REPLY, "annotations": []}+ ],+ },+ },+ {+ "type": "response.completed",+ "response": {+ "id": "resp_auth_ok",+ "usage": {+ "input_tokens": 100,+ "input_tokens_details": {"cached_tokens": 0},+ "output_tokens": 10,+ "total_tokens": 110,+ },+ },+ },+ ]++ mock = CodexMock(events_for_request=events, raw_for_request=raw)+ port = mock.start()+ try:+ harness_dir = os.path.join(tmp, ".harness")+ os.makedirs(harness_dir)+ with open(os.path.join(harness_dir, "settings.json"), "w", encoding="utf-8") as fh:+ json.dump({"ai_title": False, "skills": {"codedbpro": False}}, fh)++ env = {+ "HOME": tmp,+ "CODEX_HOME": codex_home,+ "GRAFF_CODEX_URL": f"http://127.0.0.1:{port}/backend-api/codex/responses",+ "GRAFF_CODEX_WS": "off",+ "GRAFF_FLEET": "off",+ "GRAFF_NO_TELEMETRY": "1",+ }+ ambient = tuple(+ name+ for name in os.environ+ if (name.startswith("GRAFF_") or name.startswith("CODEX_") or name == "NO_COLOR")+ and name not in env+ )+ with PtySession(+ GRAFF,+ ["--model", "codex", "--no-telemetry"],+ cwd=tmp,+ env=env,+ unset_env=ambient,+ timeout=20.0,+ ) as session:+ session.wait_for_literal("] ›")+ cursor = len(session.raw)+ session.send_line("say hello")+ session.wait_for_literal(FINAL_REPLY, start=cursor)+ session.wait_for_literal("] ›", start=cursor)+ session.send_key("ctrl-d")+ result = session.read_until_exit(5.0)+ if result.timed_out or result.exit_code != 0:+ raise AssertionError(+ f"session exit={result.exit_code} timed_out={result.timed_out}"+ )++ requests = mock.recorded_requests()+ if len(requests) < 2:+ raise AssertionError(+ f"the 401 was terminal — no retry was sent: {[r.ordinal for r in requests]!r}"+ )+ first = requests[0].headers.get("authorization", "")+ if first != f"Bearer {EXPIRED_TOKEN}":+ raise AssertionError(f"first attempt did not use the stored token: {first!r}")+ retried = requests[1].headers.get("authorization", "")+ if retried != f"Bearer {FRESH_TOKEN}":+ raise AssertionError(+ f"the retry did not carry the refreshed bearer: {retried!r}"+ )+ account = requests[1].headers.get("chatgpt-account-id", "")+ if account != EXPIRED_ACCOUNT:+ raise AssertionError(f"account header lost on the retry: {account!r}")+ # The adopted credential must also be the one every LATER request uses,+ # not just this one retry.+ for request in requests[1:]:+ token = request.headers.get("authorization", "")+ if token != f"Bearer {FRESH_TOKEN}":+ raise AssertionError(+ f"request {request.ordinal} fell back to a stale token: {token!r}"+ )+ finally:+ mock.stop()++ print("ok an expired codex token is adopted mid-turn and the retry carries it")+++if __name__ == "__main__":+ main()diff --git a/src/agent_request.zig b/src/agent_request.zigindex 432b5b5a..1461038a 100644--- a/src/agent_request.zig+++ b/src/agent_request.zig@@ -111,13 +111,14 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {// #402: codex joins this path. Its on-disk read is unconditional (a ChatGPT// token carries no expiry we can cheaply check), which is also codex-rs's// STEP 1 — a `graff login` in another terminal is picked up here, without- // waiting for a 401.+ // waiting for a 401. It reads the ONE credential dir every login flow writes+ // (oauth.codexHomeDir), so this can no longer revert a login that just+ // succeeded, and it needs neither the root's catalog nor a `home`.if (self.provider.source == .login) {- if (oauth.refreshOAuthKey(self.io, self.gpa, self.scratchAlloc(), self.home, self.provider.id, false, null, policy.codexHome(self))) |fresh| {- // Only re-dupe on a real change: this runs every request, and the+ if (oauth.refreshOAuthKey(self.io, self.gpa, self.scratchAlloc(), self.home, self.provider.id, false, null, self.provider.account)) |fresh| {+ // Only adopt on a real change: this runs every request, and the// session arena is never reclaimed.- if (!std.mem.eql(u8, fresh, self.provider.api_key))- self.provider.api_key = self.arena.dupe(u8, fresh) catch self.provider.api_key;+ if (!std.mem.eql(u8, fresh.key, self.provider.api_key)) policy.adoptFreshAuth(self, fresh);}}// #95: scrub any malformed function_call_output before it hits the wire.diff --git a/src/agent_request_policy.zig b/src/agent_request_policy.zigindex 459e1f66..582a2ee6 100644--- a/src/agent_request_policy.zig+++ b/src/agent_request_policy.zig@@ -6,6 +6,7 @@ const Agent = @import("agent.zig").Agent;const http = @import("http.zig");const RetryPlan = http.RetryPlan;const oauth = @import("oauth.zig");+const oauth_helpers = @import("oauth_helpers.zig"); // tests pin g_codex_home, the resolver startup setsconst telemetry = @import("telemetry.zig");const util = @import("util.zig");@@ -30,14 +31,37 @@ test "isAuthError (#148): auth failures only, not credits/rate/other" {try std.testing.expect(!isAuthError("context length exceeded"));}-/// The CODEX_HOME this session authenticated against. startup.zig resolves-/// $CODEX_HOME once and parks it on the catalog; the login flows instead always-/// write ~/.codex, which is the `null` fallback inside refreshOAuthKey. Reading-/// or writing the other one would silently refresh a credential the session is-/// not using.-pub fn codexHome(self: *Agent) ?[]const u8 {- const catalog = self.model_catalog orelse return null;- return if (catalog.codex_home.len > 0) catalog.codex_home else null;+/// Bind a refreshed credential to the LIVE provider. The ChatGPT account id+/// travels WITH the token: it is the chatgpt-account-id header on every codex+/// request (http_headers.zig, agent_ws.zig), so a new bearer paired with the+/// previous account's id just 401/403s again. Both are duped onto the session+/// arena — the refresh internals are scratch (#124), and a /login caller's arena+/// may be scoped.+///+/// Called only when the credential actually CHANGED, which is also why the WS+/// transport latch is released here: an expired bearer fails the WebSocket+/// HANDSHAKE, and that failure never reaches the `.responses` error arm where+/// this recovery lives — postLive counts it as a transport failure and latches+/// `ws_off` (persistent SSE) for the rest of the session (agent_ws.zig). Those+/// failures belonged to the credential; a credential that just changed earns the+/// transport back, and the existing ladder re-latches after two fresh failures+/// if the socket really was the problem.+pub fn adoptFreshAuth(self: *Agent, fresh: oauth.FreshKey) void {+ self.provider.api_key = self.arena.dupe(u8, fresh.key) catch self.provider.api_key;+ if (fresh.account.len > 0 and !std.mem.eql(u8, fresh.account, self.provider.account))+ self.provider.account = self.arena.dupe(u8, fresh.account) catch self.provider.account;+ self.ws_off = false;+ self.ws_transport_failures = 0;+}++/// A grant succeeded but its rotated credential could not be written back.+/// OpenAI kills the old refresh_token the moment the new one is issued, so the+/// in-memory token is now the only live credential: say so, instead of letting+/// the next session start logged out with no explanation.+fn warnUnpersistedRefresh(self: *Agent) void {+ const name = oauth.takePersistError() orelse return;+ if (self.tracer) |tr| tr.note("oauth_refresh", "refreshed token could not be written to auth.json");+ self.say("[⚠ refreshed the Codex token but could not save it ({s}) — run `graff login codex` before your next session]\n", .{name}) catch {};}/// #148/#402: a login-sourced credential was rejected. Adopt a token an@@ -50,15 +74,15 @@ pub fn codexHome(self: *Agent) ?[]const u8 {/// dead credential fails the turn instead of re-sending a full history forever/// — the #402 symptom, where every user message re-fired a ~302KB turn body and/// a ~868KB compaction body. A refresh that hands back the SAME token could not-/// have helped either, so it does not earn a retry.+/// have helped either, so it does not earn a retry. Neither does a credential+/// belonging to a DIFFERENT ChatGPT account (refreshOAuthKey returns null).pub fn retryAfterAuthRefresh(self: *Agent, msg: []const u8, refreshed: *bool) bool {if (refreshed.* or self.provider.source != .login or !isAuthError(msg)) return false;refreshed.* = true;- const fresh = oauth.refreshOAuthKey(self.io, self.gpa, self.scratchAlloc(), self.home, self.provider.id, true, self.provider.api_key, codexHome(self)) orelse return false;- if (std.mem.eql(u8, fresh, self.provider.api_key)) return false;- // #124: dupe off the scratch refresh internals — the key must survive every- // later request of the session.- self.provider.api_key = self.arena.dupe(u8, fresh) catch self.provider.api_key;+ const fresh = oauth.refreshOAuthKey(self.io, self.gpa, self.scratchAlloc(), self.home, self.provider.id, true, self.provider.api_key, self.provider.account) orelse return false;+ warnUnpersistedRefresh(self);+ if (std.mem.eql(u8, fresh.key, self.provider.api_key)) return false;+ adoptFreshAuth(self, fresh);if (self.tracer) |tr| tr.note("oauth_refresh", "auth error — refreshed login token, retrying");return true;}@@ -97,7 +121,36 @@ test "retryAfterAuthRefresh (#402): one attempt per request, login-sourced auth}}-test "retryAfterAuthRefresh (#402): a codex 401 adopts the token /login wrote, then stops" {+/// A subagent-shaped agent: `model_catalog` is root-only (agent.zig) and+/// `home` is never set on a child (subagent_run.zig), which is exactly the pair+/// the old code resolved the codex credential dir from.+fn testChildAgent(io: std.Io, arena: std.mem.Allocator, account: []const u8) Agent {+ var agent: Agent = undefined;+ agent.io = io;+ agent.gpa = std.testing.allocator;+ agent.arena = arena;+ agent.scratch_arena = null;+ agent.home = "";+ agent.model_catalog = null;+ agent.sub = true;+ agent.out = null;+ agent.label = "child";+ agent.tracer = null;+ agent.ws_off = true; // the expired bearer already failed the WS handshake+ agent.ws_transport_failures = 2;+ agent.provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "expired-tok", .model = "gpt-5.6", .context = 272000, .account = account, .source = .login };+ return agent;+}++fn writeTestAuth(io: std.Io, arena: std.mem.Allocator, dir: []const u8, access: []const u8, refresh: []const u8, account: []const u8) !void {+ try std.Io.Dir.cwd().createDirPath(io, dir);+ try std.Io.Dir.cwd().writeFile(io, .{+ .sub_path = try std.fmt.allocPrint(arena, "{s}/auth.json", .{dir}),+ .data = try std.fmt.allocPrint(arena, "{{\"tokens\":{{\"access_token\":\"{s}\",\"refresh_token\":\"{s}\",\"account_id\":\"{s}\"}}}}", .{ access, refresh, account }),+ });+}++test "retryAfterAuthRefresh (#402): a codex 401 adopts the token /login wrote — subagents included" {const io = std.testing.io;var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();@@ -106,46 +159,82 @@ test "retryAfterAuthRefresh (#402): a codex 401 adopts the token /login wrote, tvar tmp = std.testing.tmpDir(.{});defer tmp.cleanup();var real_buf: [std.fs.max_path_bytes]u8 = undefined;- const codex_home = real_buf[0..try tmp.dir.realPath(io, &real_buf)];- const auth_path = try std.fmt.allocPrint(arena, "{s}/auth.json", .{codex_home});- try std.Io.Dir.cwd().writeFile(io, .{- .sub_path = auth_path,- .data =- \\{"tokens":{"access_token":"fresh-tok","refresh_token":"r1","account_id":"a"}}- ,- });+ const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];+ const env_home = try std.fmt.allocPrint(arena, "{s}/env-codex-home", .{base});+ try writeTestAuth(io, arena, env_home, "fresh-tok", "r1", "acct-1");- var agent: Agent = undefined;- agent.io = io;- agent.gpa = std.testing.allocator;- agent.arena = arena;- agent.scratch_arena = null;- agent.home = "/graff-test-no-such-home";- agent.tracer = null;- agent.model_catalog = .{ .codex_home = codex_home }; // startup's resolved $CODEX_HOME- agent.provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "expired-tok", .model = "gpt-5.6", .context = 272000, .source = .login };- const expired = "Provided authentication token is expired. Please re-authenticate.";+ const saved = oauth_helpers.g_codex_home;+ defer oauth_helpers.g_codex_home = saved;+ oauth_helpers.g_codex_home = env_home; // what startup pinned from $CODEX_HOME- // The literal issue reproduction: /login rewrote auth.json, the live session was- // still on the expired bearer. The retry must pick the new one up with no- // network call and no restart.+ // CODEX_HOME set, and the agent is a CHILD: no model catalog, no home. Both+ // recovery paths used to be unconditional no-ops here, and a long codex run+ // spends most of its wall clock inside subagents — where a token is most+ // likely to cross expiry.+ var agent = testChildAgent(io, arena, "acct-1");+ const expired = "Provided authentication token is expired. Please re-authenticate.";var refreshed = false;try std.testing.expect(retryAfterAuthRefresh(&agent, expired, &refreshed));try std.testing.expect(refreshed);try std.testing.expectEqualStrings("fresh-tok", agent.provider.api_key);+ try std.testing.expectEqualStrings("acct-1", agent.provider.account);+ // The WS handshake failures that latched persistent SSE were the expired+ // credential's; a credential that just changed earns the transport back.+ try std.testing.expect(!agent.ws_off);+ try std.testing.expectEqual(@as(u8, 0), agent.ws_transport_failures);try std.testing.expect(!retryAfterAuthRefresh(&agent, expired, &refreshed)); // bounded// A refresh that can only hand back the SAME token cannot help; retrying would// just re-send the whole history for another guaranteed 401.- try std.Io.Dir.cwd().writeFile(io, .{- .sub_path = auth_path,- .data =- \\{"tokens":{"access_token":"fresh-tok","refresh_token":"","account_id":"a"}}- ,- });+ try writeTestAuth(io, arena, env_home, "fresh-tok", "", "acct-1");var again = false;try std.testing.expect(!retryAfterAuthRefresh(&agent, expired, &again));try std.testing.expect(again); // attempt was spent, so the turn fails instead of looping++ // CODEX_HOME UNSET: the same recovery, from ~/.codex, for an agent that does+ // have a home. One resolver serves both.+ oauth_helpers.g_codex_home = "";+ const home = try std.fmt.allocPrint(arena, "{s}/home", .{base});+ try writeTestAuth(io, arena, try std.fmt.allocPrint(arena, "{s}/.codex", .{home}), "home-tok", "r2", "acct-1");+ var root = testChildAgent(io, arena, "acct-1");+ root.home = home;+ var root_refreshed = false;+ try std.testing.expect(retryAfterAuthRefresh(&root, expired, &root_refreshed));+ try std.testing.expectEqualStrings("home-tok", root.provider.api_key);+}++test "retryAfterAuthRefresh (#402): a different ChatGPT account is never adopted" {+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;+ const codex_home = real_buf[0..try tmp.dir.realPath(io, &real_buf)];+ try writeTestAuth(io, arena, codex_home, "other-tok", "r1", "acct-two");++ const saved = oauth_helpers.g_codex_home;+ defer oauth_helpers.g_codex_home = saved;+ oauth_helpers.g_codex_home = codex_home;++ // codex-rs's reload_if_account_id_matches: someone re-authenticated as a+ // SECOND ChatGPT account while this session was live. Adopting that bearer+ // under this session's chatgpt-account-id header only 401/403s again, with+ // the one recovery attempt already spent.+ var agent = testChildAgent(io, arena, "acct-one");+ var refreshed = false;+ try std.testing.expect(!retryAfterAuthRefresh(&agent, "Unauthorized", &refreshed));+ try std.testing.expect(refreshed);+ try std.testing.expectEqualStrings("expired-tok", agent.provider.api_key);+ try std.testing.expectEqualStrings("acct-one", agent.provider.account);++ // The same file IS adopted by a session that belongs to that account.+ var sibling = testChildAgent(io, arena, "acct-two");+ var sibling_refreshed = false;+ try std.testing.expect(retryAfterAuthRefresh(&sibling, "Unauthorized", &sibling_refreshed));+ try std.testing.expectEqualStrings("other-tok", sibling.provider.api_key);}/// True if `msg` is a provider's "input is over the context window" rejection,diff --git a/src/agent_ws_test.zig b/src/agent_ws_test.zigindex 695d19ed..a2246a56 100644--- a/src/agent_ws_test.zig+++ b/src/agent_ws_test.zig@@ -61,6 +61,11 @@ test "codexWsIdleExpired: fires only strictly past the idle limit (codex-ws)" {// The pure unit tests over retryAfterAuthRefresh all pass even if this call site// is deleted, so pin the site itself — same shape as the source pins in// route_policy_tests.zig / route_phase_tests.zig.+//+// A source pin proves placement, never behaviour: it would still pass against a+// stubbed-out helper. The behavioural half is scripts/test-codex-auth-recovery.py,+// which drives a real graff against the codex mock over a PTY and asserts the+// RETRIED request's Authorization header carries the newly adopted bearer.test "the codex .responses arm refreshes auth and re-anchors before resending (#402)" {const src = @embedFile("agent_request.zig");const arm_start = std.mem.indexOf(u8, src, "unparseable codex response").?;diff --git a/src/oauth.zig b/src/oauth.zigindex 58f35591..5da0fd0d 100644--- a/src/oauth.zig+++ b/src/oauth.zig@@ -50,14 +50,21 @@ pub fn loadCodexAuthFrom(io: Io, arena: Allocator, codex_home: []const u8) ?Codereturn .{ .token = token, .account = account };}-/// Default-home compatibility wrapper used by login flows that always write-/// ~/.codex/auth.json. Startup and `graff models` use loadCodexAuthFrom so a-/// user-supplied CODEX_HOME controls both credentials and the native catalog.+/// Read it from THE codex home (helpers.codexHomeDir: $CODEX_HOME, else+/// ~/.codex). #402: this used to hardcode ~/.codex, so an in-session `/login`+/// read back a different file than the request loop's refresh wrote — under+/// CODEX_HOME the login "succeeded" and the session kept its expired token.pub fn loadCodexAuth(io: Io, arena: Allocator, home: []const u8) ?CodexAuth {- const codex_home = std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch return null;- return loadCodexAuthFrom(io, arena, codex_home);+ return loadCodexAuthFrom(io, arena, helpers.codexHomeDir(arena, home) orelse return null);}+/// The one credential-directory resolver, re-exported for the callers that+/// already import oauth (startup, the request loop, the pickers).+pub const codexHomeDir = helpers.codexHomeDir;+pub const initCodexHome = helpers.initCodexHome;+pub const FreshKey = helpers.FreshKey;+pub const takePersistError = helpers.takePersistError;+// #148: how long before an OAuth access token's expiry to proactively refresh// it — wider than the old 60s so a mid-session refresh has headroom before a// turn's request would otherwise cross the expiry and 401. kimi-code uses the@@ -93,7 +100,7 @@ pub fn codexLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, revar body: []const u8 = undefined;if (refresh_only) {- const path = try std.fmt.allocPrint(arena, "{s}/.codex/auth.json", .{home});+ const path = try helpers.codexAuthPath(arena, helpers.codexHomeDir(arena, home) orelse return error.NoCodexHome);const data = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(256 * 1024)) catch {try out.print("not logged in (no {s}) — run `graff login` first\n", .{path});try out.flush();@@ -103,7 +110,7 @@ pub fn codexLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, reconst refresh = blk: {if (v == .object) if (v.object.get("tokens")) |t| if (t == .object)if (t.object.get("refresh_token")) |r| if (r == .string) break :blk r.string;- try out.writeAll("no refresh_token in ~/.codex/auth.json\n");+ try out.print("no refresh_token in {s}\n", .{path});try out.flush();return;};@@ -180,7 +187,9 @@ pub fn codexLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, reconst refresh = strFieldObj(resp, "refresh_token") orelse "";const account = accountFromIdToken(arena, id_token);try writeCodexAuth(io, arena, home, id_token, access, refresh, account);- try out.print("✓ logged into Codex (account {s}…) — wrote ~/.codex/auth.json. /model codex\n", .{account[0..@min(account.len, 8)]});+ // Name the file actually written: under $CODEX_HOME it is not ~/.codex, and+ // saying otherwise is how #402 stayed invisible for so long.+ try out.print("✓ logged into Codex (account {s}…) — wrote {s}/auth.json. /model codex\n", .{ account[0..@min(account.len, 8)], helpers.codexHomeDir(arena, home) orelse "~/.codex" });try out.flush();}@@ -355,9 +364,12 @@ pub fn loadKimiOAuth(io: Io, gpa: Allocator, arena: Allocator, home: []const u8,////// #402: codex used to be excluded here as "long-lived" — it is not, and that/// premise is what made an expired ChatGPT token unrecoverable for the life of-/// a session. `codex_home` must be the dir startup resolved from $CODEX_HOME;-/// null falls back to ~/.codex, which is what the login flows write.-pub fn refreshOAuthKey(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, provider_id: []const u8, force: bool, stale: ?[]const u8, codex_home: ?[]const u8) ?[]const u8 {+/// a session. Its credential dir comes from the ONE resolver, never from the+/// caller: the root agent's model catalog and a subagent's empty `home` used to+/// answer differently, and only one of those is the file `/login` writes.+/// `account` is this session's ChatGPT account id (empty when unknown or not+/// codex) — see loadCodexOAuth's expect_account.+pub fn refreshOAuthKey(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, provider_id: []const u8, force: bool, stale: ?[]const u8, account: []const u8) ?helpers.FreshKey {const is_kimi = std.mem.eql(u8, provider_id, "kimi");const is_xai = std.mem.eql(u8, provider_id, "xai");const is_codex = std.mem.eql(u8, provider_id, "codex");@@ -365,10 +377,11 @@ pub fn refreshOAuthKey(io: Io, gpa: Allocator, arena: Allocator, home: []const uoauth_refresh_mutex.lockUncancelable(io);defer oauth_refresh_mutex.unlock(io);if (is_codex) {- const dir = codex_home orelse (std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch return null);- return helpers.loadCodexOAuth(io, gpa, arena, dir, force, stale);+ const dir = helpers.codexHomeDir(arena, home) orelse return null;+ return helpers.loadCodexOAuth(io, gpa, arena, dir, force, stale, account);}- return if (is_kimi) loadKimiOAuth(io, gpa, arena, home, force, stale) else loadXaiOAuth(io, gpa, arena, home, force, stale);+ const key = (if (is_kimi) loadKimiOAuth(io, gpa, arena, home, force, stale) else loadXaiOAuth(io, gpa, arena, home, force, stale)) orelse return null;+ return .{ .key = key };}// xAI (Grok) OAuth — device-code flow against auth.x.ai. The OIDC discoverydiff --git a/src/oauth_helpers.zig b/src/oauth_helpers.zigindex 254ca256..1ddaf91c 100644--- a/src/oauth_helpers.zig+++ b/src/oauth_helpers.zig@@ -10,6 +10,7 @@ const Value = std.json.Value;const Allocator = std.mem.Allocator;const strFieldObj = @import("util.zig").strFieldObj;+const unixMs = @import("util.zig").unixMs;// Codex / ChatGPT OAuth client — the same client + endpoints the Codex CLI// uses. Owned here (not in oauth.zig) so the silent refresh below can reach@@ -41,39 +42,121 @@ pub fn accountFromIdToken(arena: Allocator, id_token: []const u8) []const u8 {return if (account == .string) account.string else "";}+/// THE codex credential directory for this process: `$CODEX_HOME`, or+/// `<HOME>/.codex` when it is unset. Pinned once at startup — before any+/// subcommand or session can log in — and read by every reader and writer of+/// auth.json below.+///+/// #402: there used to be two answers. The mid-turn refresh resolved+/// $CODEX_HOME off the ROOT's model catalog while every login flow hardcoded+/// ~/.codex, so with CODEX_HOME set a successful `/login` was silently REVERTED+/// by the next request's proactive re-read (the reported symptom), and a+/// subagent — which carries neither a catalog nor a `home` — resolved neither+/// and got no recovery at all. One resolver, one file, catalog or not.+pub var g_codex_home: []const u8 = "";++/// Pin it. `$CODEX_HOME` and `$HOME` are taken by value rather than as an+/// environ map so a test can drive the precedence with plain strings.+pub fn initCodexHome(arena: Allocator, env_codex_home: ?[]const u8, home: ?[]const u8) void {+ if (env_codex_home) |value| if (value.len > 0) {+ g_codex_home = value;+ return;+ };+ const h = home orelse return;+ if (h.len == 0) return;+ g_codex_home = std.fmt.allocPrint(arena, "{s}/.codex", .{h}) catch "";+}++/// Where auth.json lives. `home` is only the fallback for callers that can run+/// before startup pinned the global (and for tests); null when neither is+/// known, which every caller reads as "not logged in".+pub fn codexHomeDir(arena: Allocator, home: []const u8) ?[]const u8 {+ if (g_codex_home.len > 0) return g_codex_home;+ if (home.len == 0) return null;+ return std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch null;+}+pub fn codexAuthPath(arena: Allocator, codex_home: []const u8) ![]const u8 {return std.fmt.allocPrint(arena, "{s}/auth.json", .{codex_home});}+/// Write the credential to THE codex auth.json (codexHomeDir). `home` is its+/// pre-startup fallback only — never a second location.pub fn writeCodexAuth(io: Io, arena: Allocator, home: []const u8, id_token: []const u8, access: []const u8, refresh: []const u8, account: []const u8) !void {- const dir = try std.fmt.allocPrint(arena, "{s}/.codex", .{home});+ const dir = codexHomeDir(arena, home) orelse return error.NoCodexHome;return writeCodexAuthAt(io, arena, dir, id_token, access, refresh, account);}-/// Same, against an explicit CODEX_HOME. The silent refresh must write back to-/// the file it read: startup resolves $CODEX_HOME (startup.zig), while the login-/// flows always target ~/.codex, and refreshing the wrong file would either-/// no-op or clobber an unrelated credential.+const private_file_permissions: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) @enumFromInt(0o600) else .default_file;++/// `last_refresh` in the shape the real codex CLI stores it (serde+/// `Option<DateTime<Utc>>`). The literal "harness-login" this used to write is+/// not a timestamp — tolerable in a file only `graff login` touched, not in one+/// a silent mid-turn refresh now rewrites under the other CLI's feet.+fn rfc3339Utc(buf: *[24]u8, unix_ms: i64) []const u8 {+ const es: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@max(0, @divFloor(unix_ms, 1000))) };+ const yd = es.getEpochDay().calculateYearDay();+ const md = yd.calculateMonthDay();+ const ds = es.getDaySeconds();+ return std.fmt.bufPrint(buf, "{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}Z", .{+ yd.year, md.month.numeric(), @as(u16, md.day_index) + 1,+ ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),+ }) catch "1970-01-01T00:00:00Z";+}++/// Write the ChatGPT credential into `<codex_home>/auth.json`, PRESERVING every+/// field this harness does not own.+///+/// #402: auth.json is co-owned with the real `codex` CLI, whose AuthDotJson also+/// carries openai_api_key / agent_identity / personal_access_token /+/// bedrock_api_key. The previous write emitted a fixed four-field object and+/// destroyed the rest — survivable while only an explicit `graff login` ran it,+/// not now that a silent mid-turn refresh fires it unattended. So:+/// read-modify-write replacing ONLY the token fields, and 0600 like every other+/// credential this repo writes (oauth.writeKimiAuth).pub fn writeCodexAuthAt(io: Io, arena: Allocator, codex_home: []const u8, id_token: []const u8, access: []const u8, refresh: []const u8, account: []const u8) !void {const path = try codexAuthPath(arena, codex_home);+ var object: std.json.ObjectMap = .empty;var tokens: std.json.ObjectMap = .empty;+ if (readCodexJson(io, arena, path)) |existing| {+ object = existing;+ if (existing.get("tokens")) |t| if (t == .object) {+ tokens = t.object;+ };+ }try tokens.put(arena, "id_token", .{ .string = id_token });try tokens.put(arena, "access_token", .{ .string = access });try tokens.put(arena, "refresh_token", .{ .string = refresh });try tokens.put(arena, "account_id", .{ .string = account });- var object: std.json.ObjectMap = .empty;+ var stamp: [24]u8 = undefined;try object.put(arena, "auth_mode", .{ .string = "chatgpt" });try object.put(arena, "tokens", .{ .object = tokens });- try object.put(arena, "last_refresh", .{ .string = "harness-login" });+ try object.put(arena, "last_refresh", .{ .string = rfc3339Utc(&stamp, unixMs(io)) });var aw: Io.Writer.Allocating = .init(arena);var stringify: std.json.Stringify = .{ .writer = &aw.writer };try stringify.write(Value{ .object = object });- const file = try Io.Dir.cwd().createFile(io, path, .{});- defer file.close(io);- var write_buffer: [4096]u8 = undefined;- var writer = file.writer(io, &write_buffer);- try writer.interface.writeAll(aw.writer.buffered());- try writer.interface.flush();+ Io.Dir.cwd().createDirPath(io, codex_home) catch {}; // a freshly-pointed $CODEX_HOME+ // Stage + rename rather than truncate in place. A co-owned file that a silent+ // mid-turn refresh rewrites must never be observable half-written — by the+ // real codex CLI, or by our own next read-modify-write, which would then+ // PERSIST the loss. The staging name is per-writer (random, not a fixed+ // suffix) so two concurrent refreshers cannot interleave into one temp file.+ var rnd: [8]u8 = undefined;+ io.random(&rnd);+ const staged = try std.fmt.allocPrint(arena, "{s}.graff-{d}.tmp", .{ path, std.mem.readInt(u64, &rnd, .little) });+ {+ const file = try Io.Dir.cwd().createFile(io, staged, .{ .permissions = private_file_permissions });+ defer file.close(io);+ file.setPermissions(io, private_file_permissions) catch {};+ var write_buffer: [4096]u8 = undefined;+ var writer = file.writer(io, &write_buffer);+ try writer.interface.writeAll(aw.writer.buffered());+ try writer.interface.flush();+ }+ Io.Dir.cwd().rename(staged, Io.Dir.cwd(), path, io) catch |err| {+ Io.Dir.cwd().deleteFile(io, staged) catch {}; // never leave litter next to a credential+ return err;+ };}/// POST a urlencoded form body to an OAuth token endpoint; return the parsed@@ -122,14 +205,21 @@ pub const StoredCodexAuth = struct {account: []const u8 = "",};+/// The parsed top-level object of an auth.json, or null when it is missing or+/// unparseable. Shared by the reader and by the read-modify-write above, so the+/// fields graff does not own survive a refresh.+fn readCodexJson(io: Io, arena: Allocator, path: []const u8) ?std.json.ObjectMap {+ const data = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(256 * 1024)) catch return null;+ const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return null;+ return if (v == .object) v.object else null;+}+/// Read <codex_home>/auth.json in full. Null when missing/unparseable/empty,/// i.e. not logged in.pub fn readCodexAuth(io: Io, arena: Allocator, codex_home: []const u8) ?StoredCodexAuth {const path = codexAuthPath(arena, codex_home) catch return null;- const data = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(256 * 1024)) catch return null;- const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return null;- if (v != .object) return null;- const tokens = v.object.get("tokens") orelse return null;+ const object = readCodexJson(io, arena, path) orelse return null;+ const tokens = object.get("tokens") orelse return null;if (tokens != .object) return null;const access = strFieldObj(tokens.object, "access_token") orelse return null;if (access.len == 0) return null;@@ -156,6 +246,39 @@ pub fn permanentRefreshFailure(code: []const u8) bool {/// one extra POST, never a wrong credential.var dead_refresh_token: u64 = 0;+/// A credential the request loop may adopt: the bearer AND the ChatGPT account+/// id it belongs to. They travel together because `account` is the+/// chatgpt-account-id header on every codex request (http_headers.zig,+/// agent_ws.zig) — a new bearer paired with the previous account's id just+/// 401/403s again. Empty `account` means "unchanged / not applicable" (kimi, xai).+pub const FreshKey = struct { key: []const u8, account: []const u8 = "" };++/// Set when a refreshed credential could NOT be written back, so the caller can+/// warn. OpenAI rotates the refresh_token on the grant, which kills the old one+/// server-side the moment the POST succeeds: swallowing this write failure would+/// leave only a dead credential on disk and log the user out at next start with+/// no diagnostic (codex-rs propagates it as RefreshTokenError). `@errorName` is+/// static, so the slice outlives every arena. Written under refreshOAuthKey's+/// mutex; a concurrent reader can at worst attribute one warning to the wrong+/// agent, never miss that something failed.+pub var persist_error: ?[]const u8 = null;++pub fn takePersistError() ?[]const u8 {+ defer persist_error = null;+ return persist_error;+}++/// Persist a refreshed credential, retrying once. The failures that reach here+/// (a concurrent writer's truncate, a transient EIO) are usually not sticky;+/// a still-failing write is recorded for the caller to surface.+fn persistRefreshed(io: Io, arena: Allocator, codex_home: []const u8, id_token: []const u8, access: []const u8, refresh: []const u8, account: []const u8) void {+ writeCodexAuthAt(io, arena, codex_home, id_token, access, refresh, account) catch {+ writeCodexAuthAt(io, arena, codex_home, id_token, access, refresh, account) catch |err| {+ persist_error = @errorName(err);+ };+ };+}+/// #402: the codex sibling of oauth.loadKimiOAuth — the current ChatGPT access/// token for `codex_home`, refreshed in place when `force` (i.e. the token we/// were holding just 401'd). ChatGPT access tokens DO expire; treating them as@@ -168,26 +291,33 @@ var dead_refresh_token: u64 = 0;/// STEP 2, only then, spend the refresh_token. On a failed grant it returns the/// token it read, so the caller (which compares against the stale one) gives up/// instead of resending forever.-pub fn loadCodexOAuth(io: Io, gpa: Allocator, arena: Allocator, codex_home: []const u8, force: bool, stale: ?[]const u8) ?[]const u8 {+///+/// `expect_account` is codex-rs's `reload_if_account_id_matches`: a credential+/// minted for a DIFFERENT ChatGPT account is never adopted (null = give up,+/// which the caller surfaces as the original auth error) rather than silently+/// paired with this session's account header.+pub fn loadCodexOAuth(io: Io, gpa: Allocator, arena: Allocator, codex_home: []const u8, force: bool, stale: ?[]const u8, expect_account: []const u8) ?FreshKey {const auth = readCodexAuth(io, arena, codex_home) orelse return null;- if (supersededToken(force, auth.access, stale)) return auth.access;- if (!force or auth.refresh.len == 0) return auth.access;+ if (expect_account.len > 0 and auth.account.len > 0 and !std.mem.eql(u8, expect_account, auth.account)) return null;+ const on_disk: FreshKey = .{ .key = auth.access, .account = auth.account };+ if (supersededToken(force, auth.access, stale)) return on_disk;+ if (!force or auth.refresh.len == 0) return on_disk;const refresh_id = std.hash.Wyhash.hash(0, auth.refresh);- if (refresh_id == dead_refresh_token) return auth.access; // known dead: no round trip- const body = std.fmt.allocPrint(arena, "grant_type=refresh_token&client_id={s}&refresh_token={s}&scope={s}", .{ codex_client_id, auth.refresh, codex_scope_enc }) catch return auth.access;- const resp = oauthFormPost(io, gpa, arena, codex_token_url, body) catch return auth.access; // transient: retryable, do not cache+ if (refresh_id == dead_refresh_token) return on_disk; // known dead: no round trip+ const body = std.fmt.allocPrint(arena, "grant_type=refresh_token&client_id={s}&refresh_token={s}&scope={s}", .{ codex_client_id, auth.refresh, codex_scope_enc }) catch return on_disk;+ const resp = oauthFormPost(io, gpa, arena, codex_token_url, body) catch return on_disk; // transient: retryable, do not cacheif (resp.get("error")) |e| {if (permanentRefreshFailure(if (e == .string) e.string else "")) dead_refresh_token = refresh_id;- return auth.access;+ return on_disk;}- const access = strFieldObj(resp, "access_token") orelse return auth.access;- if (access.len == 0) return auth.access;+ const access = strFieldObj(resp, "access_token") orelse return on_disk;+ if (access.len == 0) return on_disk;const id_token = strFieldObj(resp, "id_token") orelse auth.id_token;const refresh = strFieldObj(resp, "refresh_token") orelse auth.refresh;var account = if (id_token.len > 0) accountFromIdToken(arena, id_token) else "";if (account.len == 0) account = auth.account; // a rotated grant may omit id_token- writeCodexAuthAt(io, arena, codex_home, id_token, access, refresh, account) catch {};- return access;+ persistRefreshed(io, arena, codex_home, id_token, access, refresh, account);+ return .{ .key = access, .account = account };}/// The page the Codex OAuth callback tab lands on after a successful login.@@ -247,23 +377,32 @@ test "#402: loadCodexOAuth adopts the token /login wrote instead of minting a neconst codex_home = real_buf[0..try tmp.dir.realPath(io, &real_buf)];// Not logged in: nothing to adopt or refresh, the caller keeps its own key.- try std.testing.expect(loadCodexOAuth(io, std.testing.allocator, arena, codex_home, false, null) == null);+ try std.testing.expect(loadCodexOAuth(io, std.testing.allocator, arena, codex_home, false, null, "") == null);// Proactive read (force=false): the on-disk token, no grant spent.try writeCodexAuthAt(io, arena, codex_home, "", "tok-expired", "refresh-1", "acct-1");- try std.testing.expectEqualStrings("tok-expired", loadCodexOAuth(io, std.testing.allocator, arena, codex_home, false, null).?);+ try std.testing.expectEqualStrings("tok-expired", loadCodexOAuth(io, std.testing.allocator, arena, codex_home, false, null, "acct-1").?.key);// The #402 case: `/login` (or a second graff, or the real Codex CLI) rewrote// auth.json while this session still held the old token. Recovering from that// 401 must adopt what is on disk — no network call, and no #245 rotate-kill of- // the credential the other writer just minted.- try writeCodexAuthAt(io, arena, codex_home, "", "tok-fresh", "refresh-2", "acct-2");- try std.testing.expectEqualStrings("tok-fresh", loadCodexOAuth(io, std.testing.allocator, arena, codex_home, true, "tok-expired").?);+ // the credential the other writer just minted. The account id comes WITH it:+ // it is the chatgpt-account-id header, and a new bearer under the old id 403s.+ try writeCodexAuthAt(io, arena, codex_home, "", "tok-fresh", "refresh-2", "acct-1");+ const adopted = loadCodexOAuth(io, std.testing.allocator, arena, codex_home, true, "tok-expired", "acct-1").?;+ try std.testing.expectEqualStrings("tok-fresh", adopted.key);+ try std.testing.expectEqualStrings("acct-1", adopted.account);// Same token still on disk and no refresh_token to spend: hand back what was// read so the caller can see the refresh did not help and stop.- try writeCodexAuthAt(io, arena, codex_home, "", "tok-fresh", "", "acct-2");- try std.testing.expectEqualStrings("tok-fresh", loadCodexOAuth(io, std.testing.allocator, arena, codex_home, true, "tok-fresh").?);+ try writeCodexAuthAt(io, arena, codex_home, "", "tok-fresh", "", "acct-1");+ try std.testing.expectEqualStrings("tok-fresh", loadCodexOAuth(io, std.testing.allocator, arena, codex_home, true, "tok-fresh", "acct-1").?.key);++ // codex-rs's reload_if_account_id_matches: a credential minted for ANOTHER+ // ChatGPT account is never adopted. Pairing its bearer with this session's+ // account header just 401/403s, with the one recovery attempt already spent.+ try std.testing.expect(loadCodexOAuth(io, std.testing.allocator, arena, codex_home, true, "tok-expired", "acct-other") == null);+ try std.testing.expect(loadCodexOAuth(io, std.testing.allocator, arena, codex_home, false, null, "acct-other") == null);// readCodexAuth surfaces the refresh_token that oauth.loadCodexAuthFrom drops.try writeCodexAuthAt(io, arena, codex_home, "", "tok-fresh", "refresh-3", "acct-9");@@ -287,7 +426,50 @@ test "#402: permanentRefreshFailure separates a dead refresh_token from a retryatry std.testing.expect(!permanentRefreshFailure(""));}-test "#402: writeCodexAuth targets ~/.codex while writeCodexAuthAt honours CODEX_HOME" {+test "#402: ONE resolver — the login writer and the mid-turn refresh cannot target different files" {+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;+ const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];+ const home = try std.fmt.allocPrint(arena, "{s}/home", .{base});+ const home_codex = try std.fmt.allocPrint(arena, "{s}/.codex", .{home});+ const custom = try std.fmt.allocPrint(arena, "{s}/custom-codex-home", .{base});++ const saved = g_codex_home;+ defer g_codex_home = saved;++ // CODEX_HOME unset → ~/.codex, for writer and reader alike.+ g_codex_home = "";+ initCodexHome(arena, null, home);+ try std.testing.expectEqualStrings(home_codex, codexHomeDir(arena, home).?);+ try writeCodexAuth(io, arena, home, "", "home-tok", "r", "a");+ try std.testing.expectEqualStrings("home-tok", readCodexAuth(io, arena, codexHomeDir(arena, home).?).?.access);++ // CODEX_HOME set → BOTH move to it. This is the #402 split-brain: the login+ // writer used to stay on ~/.codex while the refresh read $CODEX_HOME, so the+ // next request's proactive read reverted a login that had just succeeded.+ g_codex_home = "";+ initCodexHome(arena, custom, home);+ try std.testing.expectEqualStrings(custom, codexHomeDir(arena, home).?);+ try writeCodexAuth(io, arena, home, "", "env-tok", "r", "a");+ try std.testing.expectEqualStrings("env-tok", readCodexAuth(io, arena, codexHomeDir(arena, home).?).?.access);+ try std.testing.expectEqualStrings("home-tok", readCodexAuth(io, arena, home_codex).?.access); // the other file is untouched++ // An empty $CODEX_HOME is not a location; and with neither, there is nothing+ // to read rather than a path built from "".+ g_codex_home = "";+ initCodexHome(arena, "", home);+ try std.testing.expectEqualStrings(home_codex, g_codex_home);+ g_codex_home = "";+ try std.testing.expect(codexHomeDir(arena, "") == null);+}++test "#402: a refresh that cannot be persisted is reported, not swallowed" {const io = std.testing.io;var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();@@ -298,17 +480,76 @@ test "#402: writeCodexAuth targets ~/.codex while writeCodexAuthAt honours CODEXvar real_buf: [std.fs.max_path_bytes]u8 = undefined;const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];- // A custom CODEX_HOME must not be redirected to ~/.codex: startup reads- // $CODEX_HOME, so refreshing the wrong file would silently no-op.- const custom = try std.fmt.allocPrint(arena, "{s}/custom", .{base});- try Io.Dir.cwd().createDirPath(io, custom);- try writeCodexAuthAt(io, arena, custom, "", "at-tok", "r", "a");- try std.testing.expectEqualStrings("at-tok", readCodexAuth(io, arena, custom).?.access);-- try Io.Dir.cwd().createDirPath(io, try std.fmt.allocPrint(arena, "{s}/.codex", .{base}));- try writeCodexAuth(io, arena, base, "", "home-tok", "r", "a");- try std.testing.expectEqualStrings("home-tok", readCodexAuth(io, arena, try std.fmt.allocPrint(arena, "{s}/.codex", .{base})).?.access);- try std.testing.expectEqualStrings("at-tok", readCodexAuth(io, arena, custom).?.access); // untouched+ // A "codex home" whose parent is a regular file: neither the mkdir nor the+ // create can succeed, however often they are retried.+ const blocker = try std.fmt.allocPrint(arena, "{s}/not-a-dir", .{base});+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = blocker, .data = "x" });+ persist_error = null;+ persistRefreshed(io, arena, try std.fmt.allocPrint(arena, "{s}/codex", .{blocker}), "id", "new", "rotated", "acct");+ // The grant already invalidated the OLD refresh_token server-side, so losing+ // this write silently would log the user out at next start with no clue why.+ try std.testing.expect(takePersistError() != null);+ try std.testing.expect(takePersistError() == null); // drained: warned once, not every request++ // A writable destination still persists silently.+ persistRefreshed(io, arena, base, "id", "new", "rotated", "acct");+ try std.testing.expect(takePersistError() == null);+ try std.testing.expectEqualStrings("new", readCodexAuth(io, arena, base).?.access);+}++test "#402: a refresh write preserves the fields the codex CLI owns" {+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;+ const codex_home = real_buf[0..try tmp.dir.realPath(io, &real_buf)];++ // auth.json as the real codex CLI writes it: fields graff knows nothing+ // about, at the top level AND inside tokens.+ try Io.Dir.cwd().writeFile(io, .{+ .sub_path = try codexAuthPath(arena, codex_home),+ .data =+ \\{"OPENAI_API_KEY":"sk-user-key","auth_mode":"chatgpt","agent_identity":"ai","tokens":{"access_token":"old","refresh_token":"r0","account_id":"acct-1","personal_access_token":"pat"},"last_refresh":"2026-01-02T03:04:05Z"}+ ,+ });++ // A silent mid-turn refresh now rewrites this file unattended. Anything it+ // does not own must survive, or graff quietly destroys the user's other+ // codex credentials on the first 401 of a session.+ try writeCodexAuthAt(io, arena, codex_home, "id2", "new", "r1", "acct-1");+ const raw = try Io.Dir.cwd().readFileAlloc(io, try codexAuthPath(arena, codex_home), arena, .limited(64 * 1024));+ const v = try std.json.parseFromSliceLeaky(Value, arena, raw, .{ .allocate = .alloc_always });+ try std.testing.expectEqualStrings("sk-user-key", strFieldObj(v.object, "OPENAI_API_KEY").?);+ try std.testing.expectEqualStrings("ai", strFieldObj(v.object, "agent_identity").?);+ const tokens = v.object.get("tokens").?.object;+ try std.testing.expectEqualStrings("pat", strFieldObj(tokens, "personal_access_token").?);+ try std.testing.expectEqualStrings("new", strFieldObj(tokens, "access_token").?);+ try std.testing.expectEqualStrings("r1", strFieldObj(tokens, "refresh_token").?);+ // last_refresh is what codex's own serde expects there (DateTime<Utc>), not+ // the old literal "harness-login", which would fail ITS parse of the file.+ const stamp = strFieldObj(v.object, "last_refresh").?;+ try std.testing.expectEqual(@as(usize, 20), stamp.len);+ try std.testing.expect(stamp[10] == 'T' and stamp[19] == 'Z');++ var buf: [24]u8 = undefined;+ try std.testing.expectEqualStrings("2026-08-05T12:34:56Z", rfc3339Utc(&buf, 1_785_933_296_000));+ try std.testing.expectEqualStrings("1970-01-01T00:00:00Z", rfc3339Utc(&buf, 0));++ // The write stages + renames, so a reader never sees a half-written+ // credential — and the staging file is never left next to it.+ var dir = try Io.Dir.cwd().openDir(io, codex_home, .{ .iterate = true });+ defer dir.close(io);+ var it = dir.iterate();+ var names: usize = 0;+ while (try it.next(io)) |entry| {+ try std.testing.expectEqualStrings("auth.json", entry.name);+ names += 1;+ }+ try std.testing.expectEqual(@as(usize, 1), names);}pub fn openBrowser(io: Io, url: []const u8) void {diff --git a/src/picker_auth.zig b/src/picker_auth.zigindex a9ebf512..e56ddb4e 100644--- a/src/picker_auth.zig+++ b/src/picker_auth.zig@@ -11,6 +11,8 @@ const style = &ansi.style;const term = @import("term.zig");const tty = term.tty;const oauth = @import("oauth.zig");+const oauth_helpers = @import("oauth_helpers.zig"); // the test pins g_codex_home, the resolver startup sets+const policy = @import("agent_request_policy.zig");const providers = @import("providers.zig");const switchProvider = providers.switchProvider;const agent_mod = @import("agent.zig");@@ -75,13 +77,17 @@ pub fn reloadLoginKey(root: *Agent, keys: *Keys, arena: Allocator, provider_id:// and every following turn (plus its auto-compaction) kept 401ing. The// provider.id guard is what keeps `/login kimi` from hijacking a live codex// session; the model-picker path re-assigns via switchProvider anyway.- if (reloaded and std.mem.eql(u8, root.provider.id, provider_id)) {- const key = value.* orelse continue;- root.provider.api_key = root.arena.dupe(u8, key) catch key;+ //+ // adoptFreshAuth is the same binding the mid-turn refresh uses: it dupes+ // BOTH the key and the account id onto the session arena (this function's+ // `arena` parameter can be a scoped caller arena, and account outlives it),+ // and releases the WS transport latch the expired credential earned.+ if (reloaded) if (value.*) |key| if (std.mem.eql(u8, root.provider.id, provider_id)) {+ const is_codex = std.mem.eql(u8, provider_id, "codex");+ policy.adoptFreshAuth(root, .{ .key = key, .account = if (is_codex) keys.codex_account else "" });root.provider.source = .login;- if (std.mem.eql(u8, provider_id, "codex")) root.provider.account = keys.codex_account;root.closeCodexWs(); // the held socket was dialed with the stale bearer- }+ };}if (std.mem.eql(u8, provider_id, "codex") and keys.get("codex") != null)root.reloadModelCatalog(keys.*);@@ -105,10 +111,19 @@ test "#402: reloadLoginKey hot-reloads the ACTIVE agent's credential, not just K,});+ const saved_codex_home = oauth_helpers.g_codex_home;+ defer oauth_helpers.g_codex_home = saved_codex_home;+ oauth_helpers.g_codex_home = ""; // CODEX_HOME unset: ~/.codex+var root: Agent = undefined;root.io = io;root.gpa = std.testing.allocator;root.arena = arena;+ root.scratch_arena = null;+ root.tracer = null;+ root.sub = false;+ root.out = null;+ root.label = "root";root.home = home;root.model_catalog = null; // the catalog reload would go to the networkroot.codex_ws = null;@@ -138,6 +153,32 @@ test "#402: reloadLoginKey hot-reloads the ACTIVE agent's credential, not just Ktry std.testing.expectEqualStrings("codex", root.provider.id);try std.testing.expect(root.codex_prev_id != null);std.testing.allocator.free(root.codex_prev_id.?);+ root.codex_prev_id = null;++ // The #402 split-brain: with CODEX_HOME set, `/login` must read back the very+ // file the request loop's refresh reads and writes. Before the fix this half+ // stayed on ~/.codex while the refresh resolved $CODEX_HOME, so `/login`+ // reported success and the next request's proactive read silently reverted the+ // session to the expired token.+ const custom = try std.fmt.allocPrint(arena, "{s}/custom-codex-home", .{home});+ try Io.Dir.cwd().createDirPath(io, custom);+ try Io.Dir.cwd().writeFile(io, .{+ .sub_path = try std.fmt.allocPrint(arena, "{s}/auth.json", .{custom}),+ .data =+ \\{"tokens":{"access_token":"env-tok","refresh_token":"","account_id":"acct-3"}}+ ,+ });+ oauth_helpers.g_codex_home = custom;+ root.provider.api_key = "expired-tok";+ reloadLoginKey(&root, &keys, arena, "codex");+ try std.testing.expectEqualStrings("env-tok", root.provider.api_key);+ try std.testing.expectEqualStrings("acct-3", root.provider.account);++ // …and the mid-turn recovery resolves the SAME file, so it cannot undo the+ // login it just observed.+ var refreshed = false;+ try std.testing.expect(!policy.retryAfterAuthRefresh(&root, "Unauthorized", &refreshed));+ try std.testing.expectEqualStrings("env-tok", root.provider.api_key);}/// Read an API key without terminal echo or history persistence. The ordinarydiff --git a/src/startup.zig b/src/startup.zigindex be39eb3a..a4994cd7 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -176,9 +176,7 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp// var. The same directory is used for native model-catalog discovery.var codex_account: ?[]const u8 = null;if (keys_cli.homeEnv(environ_map)) |home| {- const codex_home = environ_map.get("CODEX_HOME") orelse- (std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch "");- if (oauth.loadCodexAuthFrom(io, arena, codex_home)) |auth| {+ if (oauth.loadCodexAuthFrom(io, arena, oauth.codexHomeDir(arena, home) orelse "")) |auth| {for (provider_mod.provider_specs, &keys.values, &keys.sources) |spec, *value, *source| {if (std.mem.eql(u8, spec.id, "codex")) {value.* = auth.token;@@ -231,9 +229,7 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp} else keys_cli.loadMissingStoredKeys(io, gpa, arena, home, &keys, .all);}const home = keys_cli.homeEnv(environ_map) orelse "";- const codex_home = environ_map.get("CODEX_HOME") orelse- (std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch "");- var model_catalog: models_cache.LazyCodexCatalog = .{ .codex_home = codex_home };+ var model_catalog: models_cache.LazyCodexCatalog = .{ .codex_home = oauth.codexHomeDir(arena, home) orelse "" };const saved_model: ?serde.SavedModel = if (model_flag == null) serde.loadModel(io, arena, home) else null;// Dynamic Codex discovery is observable only when startup may select// Codex. Explicit/saved non-Codex launches defer the version subprocess,@@ -437,6 +433,11 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process}router_config.load(io, arena) catch |err|std.process.fatal("invalid {s}: {s}", .{ router_config.path, @errorName(err) });+ // #402: pin THE codex credential directory ($CODEX_HOME, else ~/.codex) before+ // anything can read or write auth.json — `graff login` is dispatched below,+ // and every later reader (startup, /login, the mid-turn refresh, subagents)+ // resolves through this one answer instead of guessing.+ oauth.initCodexHome(arena, init.environ_map.get("CODEX_HOME"), keys_cli.homeEnv(init.environ_map));// `harness key set <provider> <key>` / `harness key list`: safe key store// (macOS Keychain, else a 0600 file). Exits after.@@ -546,8 +547,7 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process// pull fresh metadata; route dry-runs provider seating on the same caches.if (flags.positionals.items.len > 0 and (std.mem.eql(u8, flags.positionals.items[0], "models") or std.mem.eql(u8, flags.positionals.items[0], "route"))) {const home = keys_cli.homeEnv(init.environ_map) orelse std.process.fatal("no HOME/USERPROFILE", .{});- const codex_home = init.environ_map.get("CODEX_HOME") orelse- (std.fmt.allocPrint(arena, "{s}/.codex", .{home}) catch "");+ const codex_home = oauth.codexHomeDir(arena, home) orelse "";const codex_auth = oauth.loadCodexAuthFrom(io, arena, codex_home);const refreshing = flags.positionals.items.len > 1 and(std.mem.eql(u8, flags.positionals.items[1], "refresh") or