Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python
26.2 KB
Raw Blame
//! OAuth login and credential loaders shared by the engine and its clients.
//! Native subscription credentials and Console SDK profiles refresh separately.

const std = @import("std");
const builtin = @import("builtin");
const Io = std.Io;
const Value = std.json.Value;
const Allocator = std.mem.Allocator;

const helpers = @import("oauth_helpers.zig");
const b64url = helpers.b64url;
const accountFromIdToken = helpers.accountFromIdToken;
const writeCodexAuth = helpers.writeCodexAuth;
const codex_login_page_html = helpers.codex_login_page_html;
const queryParam = helpers.queryParam;
const signin_link = @import("signin_link.zig");
const callback = @import("oauth_callback.zig");

const ansi = @import("ansi.zig");
const style = &ansi.style;
const Style = ansi.Style;

const util = @import("util.zig");
const strFieldObj = util.strFieldObj;

const unixMs = util.unixMs;
const codegraff = @import("oauth_codegraff.zig");
const zai = @import("oauth_zai.zig");
const credential_store = @import("credential_store.zig");

pub const CodexAuth = struct { token: []const u8, account: []const u8 };

/// Read the Codex CLI's ChatGPT OAuth credentials from <codex_home>/auth.json.
/// Returns the access token + account id (for the chatgpt-account-id header),
/// or null if the file is missing/unparseable (i.e. not logged in).
pub fn loadCodexAuthFrom(io: Io, arena: Allocator, codex_home: []const u8) ?CodexAuth {
    const path = std.fmt.allocPrint(arena, "{s}/auth.json", .{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;
    if (tokens != .object) return null;
    const token = if (tokens.object.get("access_token")) |t| (if (t == .string) t.string else return null) else return null;
    if (token.len == 0) return null;
    const account = if (tokens.object.get("account_id")) |a| (if (a == .string) a.string else "") else "";
    return .{ .token = token, .account = account };
}

/// 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 {
    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 initHome = credential_store.initHome; // #477: the kimi/xai half of the one-resolver pin
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
// same "ensureFresh near expiry + force-refresh on 401" shape.
pub const oauth_refresh_margin_s: i64 = 300;
// Serializes concurrent token refreshes (parallel subagents share the on-disk
// token) so they don't race the single-use refresh_token.
var oauth_refresh_mutex: Io.Mutex = .init;

// Codex / ChatGPT OAuth (PKCE) — same client + endpoints the Codex CLI uses
// (verified from the live id_token: aud/client_id app_EMoamEEZ…, iss
// auth.openai.com). `harness login` runs the browser flow; `harness login
// --refresh` refreshes the stored token (no browser).
const oauth_authorize_url = "https://auth.openai.com/oauth/authorize";
const oauth_token_url = helpers.codex_token_url;
const codex_client_id = helpers.codex_client_id;
const codex_redirect = "http://localhost:1455/auth/callback";
const codex_redirect_enc = "http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback";
const oauth_scope_enc = helpers.codex_scope_enc;

/// POST a form body to the OAuth token endpoint; return the parsed JSON object.
fn oauthTokenPost(io: Io, gpa: Allocator, arena: Allocator, body: []const u8) !std.json.ObjectMap {
    return helpers.oauthFormPost(io, gpa, arena, oauth_token_url, body);
}

/// `harness login [--refresh]`: the ChatGPT/Codex OAuth flow. Fresh login runs
/// PKCE (open browser → localhost:1455 callback → code→token exchange); refresh
/// uses the stored refresh_token. Either way writes ~/.codex/auth.json.
pub fn codexLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, refresh_only: bool) !void {
    var obuf: [4096]u8 = undefined;
    var ow = Io.File.stdout().writer(io, &obuf);
    const out = &ow.interface;

    var body: []const u8 = undefined;
    if (refresh_only) {
        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();
            return;
        };
        const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return error.BadOAuthResponse;
        const 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.print("no refresh_token in {s}\n", .{path});
            try out.flush();
            return;
        };
        body = try std.fmt.allocPrint(arena, "grant_type=refresh_token&client_id={s}&refresh_token={s}&scope={s}", .{ codex_client_id, refresh, oauth_scope_enc });
        try out.writeAll("refreshing Codex token…\n");
        try out.flush();
    } else {
        var vbytes: [48]u8 = undefined;
        io.random(&vbytes);
        const verifier = b64url(arena, &vbytes);
        var ch: [32]u8 = undefined;
        std.crypto.hash.sha2.Sha256.hash(verifier, &ch, .{});
        const challenge = b64url(arena, &ch);
        var sbytes: [16]u8 = undefined;
        io.random(&sbytes);
        const state = b64url(arena, &sbytes);

        const url = try std.fmt.allocPrint(arena, "{s}?response_type=code&client_id={s}&redirect_uri={s}&scope={s}&code_challenge={s}&code_challenge_method=S256&state={s}&id_token_add_organizations=true&codex_cli_simplified_flow=true", .{ oauth_authorize_url, codex_client_id, codex_redirect_enc, oauth_scope_enc, challenge, state });

        // Bind the callback port BEFORE opening the browser, so the redirect
        // can't arrive before we're listening.
        var server = try callback.listen(io, 1455);
        defer server.deinit(io);

        try out.print("\nOpen this URL to authorize (browser should open automatically):\n\n{s}\n", .{url});
        try signin_link.offer(io, out, url);
        try out.print("\nwaiting for the callback on {s} …\n", .{codex_redirect});
        try out.flush();
        signin_link.open(io, url);

        // Only this attempt's redirect ends the wait (oauth_callback.zig).
        var rbuf: [16 * 1024]u8 = undefined;
        const cb = callback.wait(io, &server, "/auth/callback", state, &rbuf) catch |err| {
            if (err != error.Cancelled) return err;
            try out.writeAll("✗ sign-in cancelled: a newer login took over the callback port\n");
            try out.flush();
            return;
        };
        defer cb.stream.close(io);
        const code = queryParam(cb.line, "code") orelse {
            callback.answer(io, cb.stream, "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\nSign-in failed. Return to the terminal.\n");
            try out.print("✗ sign-in failed: {s}\n", .{queryParam(cb.line, "error") orelse "no authorization code in the callback"});
            try out.flush();
            return;
        };
        // Branded, dark-mode-aware confirmation card (charset utf-8 so the ✓/◆
        // render) so the callback tab shows a real "you're all set" page.
        callback.answer(io, cb.stream, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nConnection: close\r\n\r\n" ++ codex_login_page_html);
        body = try std.fmt.allocPrint(arena, "grant_type=authorization_code&client_id={s}&code={s}&redirect_uri={s}&code_verifier={s}", .{ codex_client_id, code, codex_redirect_enc, verifier });
    }

    const resp = oauthTokenPost(io, gpa, arena, body) catch |err| {
        try out.print("✗ token exchange failed: {t}\n", .{err});
        try out.flush();
        return;
    };
    if (resp.get("error")) |e| {
        const msg = if (e == .string) e.string else "unknown";
        const desc = if (resp.get("error_description")) |d| (if (d == .string) d.string else "") else "";
        try out.print("✗ OAuth error: {s} {s}\n", .{ msg, desc });
        try out.flush();
        return;
    }
    const access = strFieldObj(resp, "access_token") orelse return error.BadOAuthResponse;
    const id_token = strFieldObj(resp, "id_token") orelse "";
    const refresh = strFieldObj(resp, "refresh_token") orelse "";
    const account = accountFromIdToken(arena, id_token);
    try writeCodexAuth(io, arena, home, id_token, access, refresh, account);
    // 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();
}

// Kimi Code OAuth lives in oauth_kimi.zig (two sign-in servers, kimi.ai and kimi.com).
const kimi = @import("oauth_kimi.zig");
pub const kimiLogin = kimi.login;
pub const loadKimiOAuth = kimi.load;

/// #245 single-flight guard: has the token that just 401'd already been replaced
/// on disk by another concurrent refresher? Defined in oauth_helpers.zig, where
/// the silent codex refresh (#402) needs the same primitive.
const supersededToken = helpers.supersededToken;

/// #148: mid-session refresh for a login-sourced key. For the refreshable OAuth
/// providers (kimi/xai/codex) returns the current access token, refreshed in
/// place if near expiry or `force`d (e.g. after a 401). Returns null for
/// providers with no auto-refresh flow (env keys, the long-lived codegraff
/// token), so the caller keeps the key it has. Mutex-guarded so concurrent
/// subagents don't double-refresh.
///
/// #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. 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 {
    return refreshOAuthKeyForSource(io, gpa, arena, home, provider_id, force, stale, account, .login);
}

/// Refresh only the selected credential class; never cross Console/native stores.
pub fn refreshOAuthKeyForSource(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, provider_id: []const u8, force: bool, stale: ?[]const u8, account: []const u8, source: @import("provider.zig").Keys.CredentialSource) ?helpers.FreshKey {
    if (!source.canRefresh()) return null;
    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");
    const is_chatgpt = std.mem.eql(u8, provider_id, "chatgpt-new");
    const is_anthropic = std.mem.eql(u8, provider_id, "anthropic");
    if (!is_kimi and !is_xai and !is_codex and !is_chatgpt and !is_anthropic) return null;
    oauth_refresh_mutex.lockUncancelable(io);
    defer oauth_refresh_mutex.unlock(io);
    if (is_anthropic and source == .profile) return .{ .key = @import("anthropic_profile.zig").fresh(io, gpa, arena, force) orelse return null };
    // The ChatGPT plan's new sign-in keeps one record per machine (ADR 0221),
    // so the login vault never syncs it.
    if (is_chatgpt) return .{ .key = @import("oauth_chatgpt.zig").loadChatgptOAuth(io, gpa, arena, home, force, stale) orelse return null };
    if (is_anthropic) return .{ .key = @import("oauth_anthropic.zig").loadAnthropicOAuth(io, gpa, arena, home, force, stale) orelse return null };
    // Vault sync (harness ADR 0005): adopt a newer login, wait while another
    // device refreshes, or refresh under the lease and publish the result.
    const live = @import("vault_live.zig").before(io, gpa, arena, home, provider_id, force, oauth_refresh_margin_s);
    if (live) |l| if (l.step == .wait) return null;
    const refresh_now = force and (live == null or live.?.step == .refresh);
    defer if (live) |l| l.commit();
    if (is_codex) {
        const dir = helpers.codexHomeDir(arena, home) orelse return null;
        return helpers.loadCodexOAuth(io, gpa, arena, dir, refresh_now, stale, account);
    }
    const key = (if (is_kimi) loadKimiOAuth(io, gpa, arena, home, refresh_now, stale) else loadXaiOAuth(io, gpa, arena, home, refresh_now, stale)) orelse return null;
    return .{ .key = key };
}

// xAI (Grok) OAuth — device-code flow against auth.x.ai. Parity with
// xai-org/grok-build (device_code.rs + config.rs): same public client_id, issuer,
// frozen 10-scope set, referrer, and device-code endpoint. No secret/PKCE —
// the OIDC discovery doc advertises a public ("none") client. `graff login xai`
// writes ~/.xai/credentials/graff-oauth.json; loadXaiOAuth refreshes near
// expiry. Inference uses api.x.ai with Bearer + X-XAI-Token-Auth (http_headers)
// for login tokens; bare Bearer for XAI_API_KEY. User-Agent on OAuth posts
// (Cloudflare-fronted).
const xai_oauth_host = "https://auth.x.ai";
const xai_device_auth_url = xai_oauth_host ++ "/oauth2/device/code";
const xai_token_url = xai_oauth_host ++ "/oauth2/token";
const xai_client_id = "b1a00492-073a-47ea-816f-4c329264a828";
// Frozen OAuth client scope contract (grok-build default_oauth2_scopes). Form
// body uses `+` for spaces (application/x-www-form-urlencoded).
const xai_scope_form = "openid+profile+email+offline_access+grok-cli:access+api:access+conversations:read+conversations:write+workspaces:read+workspaces:write";
const xai_user_agent = "grok-cli/1.0";
const xai_referrer = "grok-build";

/// POST a form body to an xAI OAuth endpoint (with a CLI User-Agent); return the
/// parsed JSON object.
fn xaiOAuthPost(io: Io, gpa: Allocator, arena: Allocator, url: []const u8, body: []const u8) !std.json.ObjectMap {
    var client: std.http.Client = .{ .allocator = gpa, .io = io };
    defer client.deinit();
    var aw: Io.Writer.Allocating = .init(arena);
    _ = try client.fetch(.{
        .location = .{ .url = url },
        .method = .POST,
        .payload = body,
        .response_writer = &aw.writer,
        .headers = .{
            .content_type = .{ .override = "application/x-www-form-urlencoded" },
            .user_agent = .{ .override = xai_user_agent },
        },
    });
    const v = try std.json.parseFromSliceLeaky(Value, arena, aw.writer.buffered(), .{ .allocate = .alloc_always });
    if (v != .object) return error.BadOAuthResponse;
    return v.object;
}

fn xaiAuthPath(arena: Allocator, home: []const u8) []const u8 {
    return credential_store.oauthPath(arena, home, ".xai");
}

fn writeXaiAuth(io: Io, arena: Allocator, home: []const u8, access: []const u8, refresh: []const u8, expires_at: i64) !void {
    return credential_store.writeOAuth(io, arena, home, ".xai", access, refresh, expires_at);
}

/// `graff login xai`: xAI/Grok device-code OAuth. Prints a verification URL +
/// user code, opens the browser, polls until the user authorizes, then stores
/// the access/refresh token. (The consent screen shows "Grok Build" — xAI's
/// shared CLI client.)
pub fn xaiLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !void {
    var obuf: [4096]u8 = undefined;
    var ow = Io.File.stdout().writer(io, &obuf);
    const out = &ow.interface;

    const da_body = try std.fmt.allocPrint(arena, "client_id={s}&scope={s}&referrer={s}", .{ xai_client_id, xai_scope_form, xai_referrer });
    const da = xaiOAuthPost(io, gpa, arena, xai_device_auth_url, da_body) catch |err| {
        try out.print("✗ xAI device authorization failed: {t}\n", .{err});
        try out.flush();
        return;
    };
    if (da.get("error")) |e| {
        try out.print("✗ {s}\n", .{if (e == .string) e.string else "device authorization error"});
        try out.flush();
        return;
    }
    const device_code = strFieldObj(da, "device_code") orelse return error.BadOAuthResponse;
    const user_code = strFieldObj(da, "user_code") orelse "";
    const verify = strFieldObj(da, "verification_uri_complete") orelse strFieldObj(da, "verification_uri") orelse "";
    const interval: i64 = if (da.get("interval")) |iv| (if (iv == .integer) @max(iv.integer, 1) else 5) else 5;

    try out.print("\nTo log in to Grok (xAI), open this URL (browser should open automatically):\n\n  {s}\n", .{verify});
    try signin_link.offer(io, out, verify);
    try out.print("\nand confirm the code:  {s}\n\nwaiting for authorization…\n", .{user_code});
    try out.flush();
    signin_link.open(io, verify);

    const poll_body = try std.fmt.allocPrint(arena, "client_id={s}&device_code={s}&grant_type=urn:ietf:params:oauth:grant-type:device_code", .{ xai_client_id, device_code });
    var attempts: usize = 0;
    while (attempts < 360) : (attempts += 1) {
        io.sleep(Io.Duration.fromSeconds(interval), .awake) catch {};
        const resp = xaiOAuthPost(io, gpa, arena, xai_token_url, poll_body) catch continue;
        if (resp.get("access_token")) |a| if (a == .string and a.string.len > 0) {
            const refresh = strFieldObj(resp, "refresh_token") orelse "";
            const expires_in: i64 = if (resp.get("expires_in")) |ei| (if (ei == .integer) ei.integer else 3600) else 3600;
            try writeXaiAuth(io, arena, home, a.string, refresh, @divTrunc(unixMs(io), 1000) + expires_in);
            try out.print("✓ logged into Grok (xAI) — wrote {s}. /model xai grok-4.7\n", .{xaiAuthPath(arena, home)});
            try out.writeAll("  note: xAI gates its OpenAI-compatible API per account — if a Grok turn 403s, your account isn't allowlisted for api.x.ai yet.\n");
            try out.flush();
            return;
        };
        const msg = if (resp.get("error")) |e| (if (e == .string) e.string else "") else "";
        if (std.mem.eql(u8, msg, "authorization_pending") or std.mem.eql(u8, msg, "slow_down")) continue;
        if (std.mem.eql(u8, msg, "expired_token")) {
            try out.writeAll("✗ the code expired — run `graff login xai` again\n");
            try out.flush();
            return;
        }
        if (msg.len > 0) {
            try out.print("✗ {s}\n", .{msg});
            try out.flush();
            return;
        }
    }
    try out.writeAll("✗ timed out waiting for authorization\n");
    try out.flush();
}

/// Reads the stored xAI OAuth access token, refreshing in place near expiry.
/// Returns null if not logged in. Mirrors loadKimiOAuth.
pub fn loadXaiOAuth(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, force: bool, stale: ?[]const u8) ?[]const u8 {
    const data = Io.Dir.cwd().readFileAlloc(io, xaiAuthPath(arena, home), arena, .limited(64 * 1024)) catch return null;
    const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return null;
    if (v != .object) return null;
    const access = strFieldObj(v.object, "access_token") orelse return null;
    const expires_at: i64 = if (v.object.get("expires_at")) |e| (if (e == .integer) e.integer else 0) else 0;
    // #245: another concurrent refresher may already have replaced the token that
    // 401'd; re-minting would rotate-kill theirs. Adopt what is on disk instead.
    if (supersededToken(force, access, stale)) return access;
    if (force or (expires_at != 0 and @divTrunc(unixMs(io), 1000) >= expires_at - oauth_refresh_margin_s)) {
        if (strFieldObj(v.object, "refresh_token")) |refresh| {
            const body = std.fmt.allocPrint(arena, "client_id={s}&grant_type=refresh_token&refresh_token={s}", .{ xai_client_id, refresh }) catch return access;
            const resp = xaiOAuthPost(io, gpa, arena, xai_token_url, body) catch return access;
            if (resp.get("access_token")) |a| if (a == .string and a.string.len > 0) {
                const new_refresh = strFieldObj(resp, "refresh_token") orelse refresh;
                const expires_in: i64 = if (resp.get("expires_in")) |ei| (if (ei == .integer) ei.integer else 3600) else 3600;
                writeXaiAuth(io, arena, home, a.string, new_refresh, @divTrunc(unixMs(io), 1000) + expires_in) catch {};
                return a.string;
            };
        }
    }
    return access;
}

pub const codegraffLogin = codegraff.login;
pub const loadCodegraffKey = codegraff.loadKey;
pub const zaiLogin = zai.login;
pub const loadZaiOAuth = zai.loadZaiOAuth;

test "b64url: url-safe base64 without padding" {
    var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena_state.deinit();
    const a = arena_state.allocator();
    try std.testing.expectEqualStrings("Zm9v", b64url(a, "foo"));
    try std.testing.expectEqualStrings("", b64url(a, ""));
    // bytes that would be '+' and '/' in standard base64 use '-' and '_', no '=' padding
    try std.testing.expectEqualStrings("-_8", b64url(a, &[_]u8{ 0xfb, 0xff }));
}
test "queryParam: extracts a value from an HTTP request line's query string" {
    try std.testing.expectEqualStrings("2", queryParam("GET /p?a=1&b=2 HTTP/1.1", "b").?);
    try std.testing.expectEqualStrings("1", queryParam("GET /p?a=1&b=2 HTTP/1.1", "a").?);
    try std.testing.expect(queryParam("GET /p?a=1 HTTP/1.1", "z") == null); // key absent
    try std.testing.expect(queryParam("GET /p HTTP/1.1", "a") == null); // no query string
}
test "accountFromIdToken: extracts chatgpt_account_id from a JWT payload" {
    var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena_state.deinit();
    const a = arena_state.allocator();
    // payload base64url-no-pad encodes
    // {"https://api.openai.com/auth":{"chatgpt_account_id":"acc_test_123"}}
    const token = "eyJhbGciOiJub25lIn0." ++
        "eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOiB7ImNoYXRncHRfYWNjb3VudF9pZCI6ICJhY2NfdGVzdF8xMjMifX0" ++
        ".sig";
    try std.testing.expectEqualStrings("acc_test_123", accountFromIdToken(a, token));
    try std.testing.expectEqualStrings("", accountFromIdToken(a, "not-a-jwt")); // no payload segment
    try std.testing.expectEqualStrings("", accountFromIdToken(a, "a.b.c")); // payload not valid base64/json
}

test "supersededToken (#245): a concurrent refresher's token is adopted, not re-minted" {
    const failed = "access-token-A";
    const replaced = "access-token-B";

    // The proactive (near-expiry) path never short-circuits — it is not recovering
    // from a 401, so there is no "failed token" to compare against.
    try std.testing.expect(!supersededToken(false, failed, failed));
    try std.testing.expect(!supersededToken(false, replaced, failed));

    // Recovering from a 401 while the on-disk token is STILL the one that failed:
    // nobody else has refreshed, so this caller must do it.
    try std.testing.expect(!supersededToken(true, failed, failed));

    // Recovering from a 401 but disk already holds a DIFFERENT token: another child
    // won the race. Re-minting here would rotate-kill their token and cascade the
    // 401s across the fleet, which is the whole bug.
    try std.testing.expect(supersededToken(true, replaced, failed));

    // A caller that cannot say which token failed keeps the old behaviour.
    try std.testing.expect(!supersededToken(true, replaced, null));
    try std.testing.expect(!supersededToken(false, replaced, null));
}

test "writeKimiAuth/writeXaiAuth: both real writers store 0600 in 0700 dirs, loadable" {
    if (builtin.os.tag == .windows) return;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{ .iterate = true });
    defer tmp.cleanup();
    var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena_state.deinit();
    const arena = arena_state.allocator();
    const home = try std.fmt.allocPrint(arena, ".zig-cache/tmp/{s}", .{&tmp.sub_path});
    const far_future = 4102444800; // year 2100: the loaders must not try to refresh

    // Drive the two production writers, not a shared helper: xAI used to open its
    // token file with a bare createFile (0644, no 0700 dirs) while kimi hardened
    // its own, and only pinning both functions keeps that from coming back.
    try kimi.writeAuth(io, arena, home, "kimi-access", "kimi-refresh", far_future, "");
    try writeXaiAuth(io, arena, home, "xai-access", "xai-refresh", far_future);

    for ([_][]const u8{ ".kimi", ".xai" }) |provider_dir| {
        const base = try tmp.dir.openDir(io, provider_dir, .{});
        defer base.close(io);
        const credentials = try base.openDir(io, "credentials", .{});
        defer credentials.close(io);
        try std.testing.expectEqual(@as(std.posix.mode_t, 0o700), (try base.stat(io)).permissions.toMode() & 0o777);
        try std.testing.expectEqual(@as(std.posix.mode_t, 0o700), (try credentials.stat(io)).permissions.toMode() & 0o777);
        try std.testing.expectEqual(@as(std.posix.mode_t, 0o600), (try credentials.statFile(io, "graff-oauth.json", .{})).permissions.toMode() & 0o777);
    }

    // …and the real loaders find what the real writers wrote, at their own paths.
    try std.testing.expectEqualStrings("kimi-access", loadKimiOAuth(io, std.testing.allocator, arena, home, false, null).?);
    try std.testing.expectEqualStrings("xai-access", loadXaiOAuth(io, std.testing.allocator, arena, home, false, null).?);
}