artifactize 0.31.0

The AI-native collaboration layer for one-of-a-kind teammates and their agents: split a project into Artifacts with their own evals, and reuse every review while it still holds.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! The `codex` backend end to end against a fake Codex endpoint and sign-in server.

#[path = "support/order.rs"]
mod order;
#[path = "support/run.rs"]
mod owned_run;

#[path = "../../artifactize-core/tests/support/mod.rs"]
mod support;
use support::runs::RecordOutput;

use std::{
    fs,
    path::{Path, PathBuf},
    process::{Command, Output},
};

use serde_json::{Value, json};
use support::{FakeProvider, Reply, Request, codex, openai};

// Provider diagnostics are clipped to this public display bound only after secret checks.
const DIAGNOSTIC_CHARS: usize = 4096;

struct Project {
    root: owned_run::Root,
    repo: PathBuf,
    state: PathBuf,
}

impl Project {
    /// One `spec` Artifact with a built-in `read` tool, a content fingerprint (so its
    /// review has a reuse key) and a `codex` Agent eval.
    fn new() -> Self {
        let root = owned_run::Root::from(support::os::tempdir());
        let repo = root.path().join("repo");
        fs::create_dir_all(repo.join("spec")).unwrap();
        fs::write(
            support::declaration::source_path(repo.join("spec/spec.md")),
            "R1: the spec covers R1.\n",
        )
        .unwrap();
        let profile = json!({
            "kind":"agent",
            "backend":"codex",
            "model":"gpt-6-luna",
            "reasoning":"max",
            "max_tool_calls":2,
        });
        support::declaration::write(
            &(repo),
            repo.join("spec/index.artf"),
            json!({"name":"spec","views":{"agent_tools":{"read":{"builtin":"read"}}},
                "fingerprint":{},
                "evals":[{"id":"review","title":"Review","profile":profile,
                    "payload":{"instruction":"Review {spec}."}}]})
            .to_string(),
        )
        .unwrap();
        let state = root.path().join("state");
        root.track(&state, &repo);
        Self { state, repo, root }
    }

    fn profile(&self, profile: Value) {
        let path = self.repo.join("spec/index.artf");
        let mut declaration: Value =
            support::declaration::read(support::declaration::read_file(&path).unwrap()).unwrap();
        declaration["evals"][0]["profile"] = profile;
        support::declaration::write(&(self.repo), path, declaration.to_string()).unwrap();
    }

    /// The Codex CLI's store in this project's own Codex home.
    fn credentials(&self) -> PathBuf {
        self.root.path().join("codex-home").join("auth.json")
    }

    /// The Codex CLI's sign-in, as `codex login` saves it.
    fn sign_in(&self, access: &str) {
        let home = self.credentials().parent().unwrap().to_path_buf();
        support::os::create_private_dir_all(&home);
        let store = json!({
            "OPENAI_API_KEY":null,
            "tokens":{
                "id_token":"id",
                "access_token":access,
                "refresh_token":"stored-refresh",
                "account_id":"account-1",
            },
            "last_refresh":"2026-10-01T00:00:00Z",
        });
        let _ = support::declaration::remove_file(self.credentials());
        support::os::write_private_file(&self.credentials(), store.to_string());
    }

    fn command(&self, args: &[&str]) -> Command {
        let mut command = Command::new(support::os::cli());
        command
            .arg("--repo")
            .arg(&self.repo)
            .arg("--state-dir")
            .arg(&self.state)
            .args(args)
            .arg("--json")
            .env("ARTIFACTIZE_REMOTE", "off")
            .env("CODEX_HOME", self.credentials().parent().unwrap())
            .env_remove("ARTIFACTIZE_CODEX_BASE_URL")
            .env_remove("ARTIFACTIZE_CODEX_AUTH_URL");
        command
    }

    fn against(&self, provider: &FakeProvider, args: &[&str]) -> Command {
        let mut command = self.command(args);
        command
            .env("ARTIFACTIZE_CODEX_BASE_URL", provider.codex_base())
            .env("ARTIFACTIZE_CODEX_AUTH_URL", &provider.url);
        command
    }
}

fn parsed(output: Output, code: i32) -> Value {
    assert_eq!(
        output.status.code(),
        Some(code),
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).unwrap()
}

fn replayed(request: &Request) -> bool {
    request.body["input"].as_array().is_some_and(|input| {
        input
            .iter()
            .any(|item| item["type"] == "function_call_output")
    })
}

/// Read `spec.md` once, then pass.
fn reviewer(request: &Request) -> Reply {
    match request.path.as_str() {
        "/backend-api/codex/responses" if replayed(request) => codex::completed(
            request,
            vec![openai::message(r#"{"issues":[]}"#)],
            openai::usage(40, 8),
        ),
        "/backend-api/codex/responses" => codex::completed(
            request,
            vec![openai::function_call(
                "call_1",
                "spec-tools_read_spec",
                &json!({"path":"spec.md"}),
            )],
            openai::usage(30, 5),
        ),
        "/oauth/token" => codex::tokens(
            &codex::jwt("account-1", codex::VALID_EXPIRY),
            "rotated-refresh",
        ),
        path => Reply::Json(
            404,
            json!({"error":{"message":format!("unexpected {path}")}}),
        ),
    }
}

fn form(request: &Request) -> Vec<(String, String)> {
    url::form_urlencoded::parse(request.body.as_str().unwrap().as_bytes())
        .into_owned()
        .collect()
}

#[test]
fn a_review_calls_tools_with_codex_headers_and_exact_max_reasoning() {
    let project = Project::new();
    let access = codex::jwt("account-1", codex::VALID_EXPIRY);
    project.sign_in(&access);
    let provider = FakeProvider::start(reviewer);
    let run = parsed(
        project
            .against(&provider, &["verify", "--wait", "--all"])
            .record_output()
            .unwrap(),
        0,
    );
    let review = &run["requests"][0];
    assert_eq!(review["status"], "GREEN", "{run}");
    // The review's tool calls live in its saved session, not in the request.
    assert!(review.get("toolCalls").is_none());
    let attempts = review["usage"].as_array().unwrap();
    assert_eq!(attempts.len(), 2);
    assert_eq!(attempts[1]["usage"]["inputTokens"], 40);

    let calls = provider.requests();
    assert_eq!(calls.len(), 2, "no refresh while the token is fresh");
    for call in &calls {
        assert_eq!(
            (call.method.as_str(), call.path.as_str()),
            ("POST", "/backend-api/codex/responses")
        );
        let headers = &call.headers;
        assert_eq!(headers["authorization"], format!("Bearer {access}"));
        assert_eq!(headers["chatgpt-account-id"], "account-1");
        assert_eq!(headers["originator"], "artifactize");
        assert_eq!(headers["openai-beta"], "responses=experimental");
        assert_eq!(headers["accept"], "text/event-stream");
        assert!(headers["user-agent"].starts_with("artifactize/"));
        // The review's session keys the prompt cache; rig's per-request `session_id` is off.
        assert_eq!(headers["session-id"], review["sessionId"].as_str().unwrap());
        assert!(!headers.contains_key("session_id"));
        let body = &call.body;
        assert_eq!(body["prompt_cache_key"], review["sessionId"]);
        assert_eq!(body["model"], "gpt-6-luna");
        assert_eq!(body["reasoning"], json!({"effort":"max","summary":"auto"}));
        assert_eq!(body["store"], false);
        assert_eq!(body["stream"], true);
        assert_eq!(body["include"], json!(["reasoning.encrypted_content"]));
        assert_eq!(body["tools"][0]["type"], "function");
        assert_eq!(body["tools"][0]["name"], "spec-tools_read_spec");
        let instructions = body["instructions"].as_str().unwrap();
        assert!(instructions.starts_with("You are an artifactize evaluator."));
        assert_eq!(body["text"]["format"]["type"], "json_schema");
        assert_eq!(body["text"]["format"]["strict"], true);
        let schema = &body["text"]["format"]["schema"];
        assert_eq!(schema["type"], "object");
        assert_eq!(schema["required"], json!(["issues"]));
        assert!(schema.get("anyOf").is_none());
        assert!(instructions.contains(
            "If a person later asks a follow-up question about this review, answer that question in plain text instead"
        ));
        assert!(!instructions.contains("You are ChatGPT"));
        for absent in ["temperature", "max_output_tokens", "metadata"] {
            assert!(body.get(absent).is_none(), "{absent}: {body}");
        }
    }
    let output = calls[1].body["input"]
        .as_array()
        .unwrap()
        .iter()
        .find(|item| item["type"] == "function_call_output")
        .unwrap();
    assert_eq!(output["call_id"], "call_1");
    assert!(output.to_string().contains("the spec covers R1"));
}

#[test]
fn an_expired_sign_in_is_refreshed_and_rotated_before_the_review() {
    let project = Project::new();
    project.sign_in(&codex::jwt("account-1", codex::EXPIRED));
    let provider = FakeProvider::start(reviewer);
    let run = parsed(
        project
            .against(&provider, &["verify", "--wait", "--all"])
            .record_output()
            .unwrap(),
        0,
    );
    assert_eq!(run["requests"][0]["status"], "GREEN", "{run}");
    let calls = provider.requests();
    let paths: Vec<_> = calls.iter().map(|call| call.path.as_str()).collect();
    assert_eq!(
        paths,
        [
            "/oauth/token",
            "/backend-api/codex/responses",
            "/backend-api/codex/responses"
        ]
    );
    assert_eq!(
        form(&calls[0]),
        [
            ("grant_type".to_owned(), "refresh_token".to_owned()),
            ("refresh_token".to_owned(), "stored-refresh".to_owned()),
            (
                "client_id".to_owned(),
                "app_EMoamEEZ73f0CkXaXp7hrann".to_owned()
            ),
        ]
    );
    // The refresh is written back to the Codex CLI's store, which keeps its other fields.
    let saved: Value =
        serde_json::from_slice(&support::declaration::read_file(project.credentials()).unwrap())
            .unwrap();
    let issued = codex::jwt("account-1", codex::VALID_EXPIRY);
    assert_eq!(saved["tokens"]["refresh_token"], "rotated-refresh");
    assert_eq!(saved["tokens"]["access_token"], issued);
    assert_eq!(saved["tokens"]["account_id"], "account-1");
    assert!(saved["OPENAI_API_KEY"].is_null());
    for call in &calls[1..] {
        assert_eq!(call.headers["authorization"], format!("Bearer {issued}"));
    }
    assert!(support::os::private_file(&project.credentials()));
}

fn failed(project: &Project, provider: &FakeProvider) -> Value {
    let run = parsed(
        project
            .against(provider, &["verify", "--wait", "--all"])
            .record_output()
            .unwrap(),
        2,
    );
    let request = run["requests"][0].clone();
    assert_eq!(request["status"], "ERROR", "{run}");
    request
}

#[test]
fn provider_errors_explain_themselves_and_permanent_ones_are_not_retried() {
    let project = Project::new();
    project.sign_in(&codex::jwt("account-1", codex::VALID_EXPIRY));

    let expired = FakeProvider::start(|_| {
        Reply::Json(
            401,
            json!({
                "error":{"message":"Your authentication token has expired.","code":"token_expired"},
            }),
        )
    });
    let request = failed(&project, &expired);
    let error = request["error"].as_str().unwrap();
    assert!(
        error.starts_with("token_expired: Your authentication token has expired. (HTTP 401)"),
        "{error}"
    );
    assert!(error.contains("`codex login`"), "{error}");
    assert_eq!(request["usage"].as_array().unwrap().len(), 1);
    assert_eq!(expired.requests().len(), 1);

    let resets = codex::EXPIRED;
    let limited = FakeProvider::start(move |_| {
        Reply::Json(
            429,
            json!({
                "error":{
                    "type":"usage_limit_reached",
                    "message":"The usage limit has been reached",
                    "plan_type":"plus",
                    "resets_at":resets,
                },
            }),
        )
    });
    let request = failed(&project, &limited);
    let error = request["error"].as_str().unwrap();
    // A fixed past reset yields zero; future-reset rounding uses injected unit clocks.
    assert!(
        error.contains("You have hit your ChatGPT usage limit (plus plan). Try again in ~0 min."),
        "{error}"
    );
    assert_eq!(limited.requests().len(), 1);

    let broken = FakeProvider::start(|_| {
        codex::stream(vec![
            json!({
                "type":"response.created",
                "sequence_number":0,
                "response":{
                    "id":"resp_1",
                    "object":"response",
                    "created_at":1,
                    "model":"gpt-6-luna",
                    "status":"in_progress",
                    "output":[],
                },
            }),
            json!({
                "type":"response.failed",
                "sequence_number":1,
                "response":{
                    "id":"resp_1",
                    "object":"response",
                    "created_at":1,
                    "model":"gpt-6-luna",
                    "status":"failed",
                    "output":[],
                    "error":{"code":"invalid_prompt","message":"The prompt was rejected."},
                },
            }),
        ])
    });
    let error = failed(&project, &broken)["error"]
        .as_str()
        .unwrap()
        .to_owned();
    assert!(error.contains("The prompt was rejected."), "{error}");

    support::declaration::remove_file(project.credentials()).unwrap();
    let unused = FakeProvider::script(Vec::new());
    let error = failed(&project, &unused)["error"]
        .as_str()
        .unwrap()
        .to_owned();
    assert!(
        error.starts_with("Codex is not signed in; run `codex login`"),
        "{error}"
    );
    assert!(unused.requests().is_empty());
}

#[test]
fn models_lists_the_accounts_picker_models_in_server_order() {
    let project = Project::new();
    project.sign_in(&codex::jwt("account-1", codex::VALID_EXPIRY));
    let provider = FakeProvider::start(|_| {
        Reply::Json(
            200,
            json!({
                "models":[
                    {
                        "slug":"gpt-6-luna",
                        "display_name":"GPT-6 Luna",
                        "visibility":"list",
                        "supported_in_api":true,
                        "supported_reasoning_levels":[{"effort":"low"}, {"effort":"high"}],
                        "default_reasoning_level":"low",
                    },
                    {"slug":"internal","display_name":"Internal","visibility":"hide"},
                    {"slug":"gpt-6.1-sol","display_name":"GPT-6.1 Sol","visibility":"list"},
                ],
            }),
        )
    });
    let listing = parsed(
        project
            .against(&provider, &["models", "codex"])
            .record_output()
            .unwrap(),
        0,
    );
    assert_eq!(
        listing,
        json!({"backend":"codex","models":[
            {"slug":"gpt-6-luna","display_name":"GPT-6 Luna","efforts":["low","high"],"default_effort":"low"},
            {"slug":"gpt-6.1-sol","display_name":"GPT-6.1 Sol","efforts":[],"default_effort":null},
        ]})
    );
    let call = &provider.requests()[0];
    assert_eq!(
        (call.method.as_str(), call.path.as_str()),
        ("GET", "/backend-api/codex/models?client_version=0.169.0")
    );
    assert_eq!(call.headers["chatgpt-account-id"], "account-1");
    assert_eq!(call.headers["originator"], "artifactize");
    assert!(call.headers["authorization"].starts_with("Bearer "));

    support::declaration::remove_file(project.credentials()).unwrap();
    let failure = parsed(
        project
            .against(&provider, &["models", "codex"])
            .record_output()
            .unwrap(),
        2,
    );
    assert!(failure["error"].as_str().unwrap().contains("`codex login`"));
}

fn check(report: &Value) -> &Value {
    let checks = report["checks"].as_array().unwrap();
    checks
        .iter()
        .find(|check| check["name"] == "codex")
        .unwrap()
}

#[test]
fn doctor_reports_the_sign_in_offline() {
    let project = Project::new();
    let doctor = |command: &mut Command, code| parsed(command.record_output().unwrap(), code);
    let report = doctor(&mut project.command(&["doctor"]), 0);
    assert_eq!(check(&report)["status"], "WARN");
    assert_eq!(check(&report)["details"]["source"], "none");

    // An expired access token still signs in while its refresh token can renew it.
    project.sign_in(&codex::jwt("account-1", codex::EXPIRED));
    let report = doctor(&mut project.command(&["doctor"]), 0);
    assert_eq!(check(&report)["status"], "PASS");
    assert_eq!(check(&report)["details"]["source"], "file");
    assert_eq!(check(&report)["details"]["expired"], false);
    assert!(!report.to_string().contains("stored-refresh"));

    let report = doctor(
        project
            .command(&["doctor"])
            .env(
                "ARTIFACTIZE_CODEX_BASE_URL",
                "http://127.0.0.1:9/backend-api/codex/",
            )
            .env("ARTIFACTIZE_CODEX_AUTH_URL", "http://localhost:9"),
        0,
    );
    let entry = check(&report);
    assert_eq!(entry["status"], "WARN");
    assert_eq!(
        entry["details"]["testEndpoint"],
        "http://127.0.0.1:9/backend-api/codex"
    );
    assert_eq!(entry["details"]["testAuthEndpoint"], "http://localhost:9");

    let report = doctor(
        project
            .command(&["doctor"])
            .env("ARTIFACTIZE_CODEX_AUTH_URL", "https://auth.openai.com"),
        1,
    );
    assert_eq!(check(&report)["status"], "FAIL");
}

#[test]
fn the_sign_in_test_endpoint_guards_the_review_store() {
    let project = Project::new();
    let failure = parsed(
        project
            .command(&["verify", "--wait", "--all"])
            .env("ARTIFACTIZE_CODEX_AUTH_URL", "http://127.0.0.1:9")
            .env("ARTIFACTIZE_REMOTE", "http://127.0.0.1:9/")
            .env("ARTIFACTIZE_REMOTE_TOKEN", "team-token")
            .record_output()
            .unwrap(),
        2,
    );
    assert!(
        failure["error"]
            .as_str()
            .unwrap()
            .contains("ARTIFACTIZE_CODEX_AUTH_URL")
    );
}

#[test]
fn removed_backend_messages_name_codex_without_a_version() {
    let project = Project::new();
    // Profiles are declared once for the project.
    let path = project.repo.join(".artifactize/profiles.artfprofiles");
    let profiles = std::fs::read_to_string(&path)
        .unwrap()
        .replace("backend = \"codex\"", "backend = \"chatgpt\"");
    std::fs::write(&path, profiles).unwrap();
    let failure = parsed(
        project
            .command(&["config", "check"])
            .record_output()
            .unwrap(),
        2,
    );
    let error = failure["error"].as_str().unwrap();
    assert!(
        error.trim_end().ends_with(
            r#"backend "chatgpt" was removed in 0.5.0; use "openai", "anthropic" or "gemini" with an API key, "codex" with the Codex CLI's sign-in, or "claude" with your Claude Code login"#
        ),
        "{error}"
    );
    assert!(!Path::new(&project.state).join("auth").exists());
}

#[test]
fn codex_and_openai_results_for_the_same_key_reuse_each_other() {
    let project = Project::new();
    project.sign_in(&codex::jwt("account-1", codex::VALID_EXPIRY));
    let provider = FakeProvider::start(|request| {
        let pass = vec![openai::message(r#"{"issues":[]}"#)];
        match request.path.as_str() {
            "/backend-api/codex/responses" => codex::completed(request, pass, openai::usage(30, 5)),
            "/v1/responses" => openai::completed(request, pass, openai::usage(20, 4)),
            path => Reply::Json(
                404,
                json!({"error":{"message":format!("unexpected {path}")}}),
            ),
        }
    });
    let verify = |args: &[&str]| {
        let mut command = project.against(&provider, args);
        command
            .env("ARTIFACTIZE_OPENAI_BASE_URL", provider.openai_base())
            .env("OPENAI_API_KEY", "fake-openai-key");
        parsed(command.record_output().unwrap(), 0)
    };
    let codex_options =
        json!({"backend":"codex","model":"gpt-6-luna","reasoning":"max","maxToolCalls":2});
    let openai_profile =
        json!({"kind":"agent","backend":"openai","model":"fake-openai-model","reasoning":"high"});

    // The codex review records its execution options beside the result.
    let first = verify(&["verify", "--wait", "--all"]);
    let produced = &first["requests"][0];
    assert_eq!(produced["status"], "GREEN", "{first}");
    assert_eq!(produced["options"], codex_options);
    let key = produced["key"].as_str().unwrap().to_owned();
    let record = verify(&["cache", "show", &key]);
    assert_eq!(record["options"], codex_options);

    // An openai profile has the same key and reuses the codex result.
    project.profile(openai_profile.clone());
    let second = verify(&["verify", "--wait", "--all"]);
    let reused = &second["requests"][0];
    assert_eq!(second["executionsStarted"], 0);
    assert_eq!(reused["key"], key);
    assert_eq!(reused["executionId"], produced["executionId"]);
    assert_eq!(reused["options"], codex_options);
    assert_eq!(reused["requestedProfile"]["backend"], "openai");
    assert_eq!(provider.requests().len(), 1);

    // A forced openai review adds a newer record, which codex then reuses.
    let forced = verify(&["verify", "--wait", "--all", "--force"]);
    let newer = &forced["requests"][0];
    assert_eq!(forced["executionsStarted"], 1);
    assert_eq!(
        newer["options"],
        json!({"backend":"openai","model":"fake-openai-model","reasoning":"high"})
    );
    assert_eq!(provider.requests()[1].path, "/v1/responses");
    // Latest-result selection follows given fixture times, not execution wall-clock order.
    for (run, completed) in [
        (&first, "2000-01-01T00:00:00.000000000Z"),
        (&forced, "2000-01-02T00:00:00.000000000Z"),
    ] {
        order::completed_at(&project.state, &project.repo, run, completed);
    }
    project.profile(json!({
        "kind":"agent",
        "backend":"codex",
        "model":"gpt-6-luna",
        "reasoning":"max",
        "max_tool_calls":2,
    }));
    let back = verify(&["verify", "--wait", "--all"]);
    assert_eq!(back["executionsStarted"], 0);
    assert_eq!(back["requests"][0]["executionId"], newer["executionId"]);
    assert_eq!(back["requests"][0]["options"]["backend"], "openai");
    assert_eq!(provider.requests().len(), 2);
}

#[test]
fn a_models_error_echoing_the_access_token_withholds_it() {
    let project = Project::new();
    let access = codex::jwt("account-1", codex::VALID_EXPIRY);
    project.sign_in(&access);
    let provider = FakeProvider::start(|request| {
        let header = request
            .headers
            .get("authorization")
            .cloned()
            .unwrap_or_default();
        // Split by a newline, which dropping control characters would rejoin.
        let (head, tail) = header.split_at(header.len() / 2);
        Reply::Json(
            400,
            json!({"error":{"message":format!("Bad header {head}\n{tail}"),"code":"bad_request"}}),
        )
    });
    let output = project
        .against(&provider, &["models", "codex"])
        .record_output()
        .unwrap();
    let failure = parsed(output.clone(), 2);
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let signature = &access[access.len() - 14..];
    let payload = &access[access.find('.').unwrap() + 1..][..12];
    for piece in [signature, payload] {
        assert!(!text.contains(piece), "{text}");
    }
    assert_eq!(
        failure["error"],
        "Codex model listing failed (HTTP 400): [withheld: it contained part of the credential sent]"
    );
}

/// The whole provider text is checked before the 4096-character clip: a token straddling the
/// clip is withheld, not cut to a prefix.
#[test]
fn a_models_error_with_the_token_at_the_clip_withholds_it() {
    let project = Project::new();
    let access = codex::jwt("account-1", codex::VALID_EXPIRY);
    project.sign_in(&access);
    let provider = FakeProvider::start(|request| {
        let token = request.headers["authorization"]
            .strip_prefix("Bearer ")
            .unwrap()
            .to_owned();
        Reply::Json(
            400,
            json!({"error":{"message":format!("{}{token}", "x".repeat(DIAGNOSTIC_CHARS - "Bearer ".len()))}}),
        )
    });
    let output = project
        .against(&provider, &["models", "codex"])
        .record_output()
        .unwrap();
    let failure = parsed(output.clone(), 2);
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(!text.contains(&access[..7]), "{text}");
    assert_eq!(
        failure["error"],
        "Codex model listing failed (HTTP 400): [withheld: it contained part of the credential sent]"
    );
}