akribes-sdk 0.22.6

Rust client SDK for the Akribes workflow server
Documentation
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
//! Integration tests for the bench sub-clients (`BenchClient` +
//! `BenchRunsClient`).
//!
//! Each test asserts the *request shape the SDK puts on the wire* (method,
//! path, query, body JSON) against what the corresponding `akribes-server`
//! bench handler parses, plus correct deserialisation of the response body.
//! The wire shapes mirror `crates/akribes-server/src/handlers/bench.rs` and
//! `crates/akribes-server/src/models.rs`.

use akribes_sdk::AkribesError;
use akribes_sdk::models::{
    CreateBenchCaseRequest, CreateOrUpdateBenchRequest, PatchBenchCaseRequest, PromoteCaseEdits,
    PromoteExecutionRequest, TriggerBenchRunRequest,
};
use akribes_sdk::{AkribesClient, BenchClient, BenchRunsClient};
use mockito::{Matcher, Server};

fn make_client(server: &Server) -> AkribesClient {
    AkribesClient::builder(server.url())
        .project_id(7)
        .name("bench-test")
        .id("bench-id")
        .build()
}

fn bench(server: &Server) -> BenchClient {
    make_client(server).project(7).bench()
}

fn runs(server: &Server) -> BenchRunsClient {
    make_client(server).bench_runs()
}

// ── Project-wide summary ──────────────────────────────────────────────────────

#[tokio::test]
async fn list_project_summaries_maps_to_projects_benches_route() {
    let mut server = Server::new_async().await;
    // GET /projects/{id}/benches — the project id comes from the scope (7),
    // NOT a query param. Mirror the server's `list_project_benches` row shape
    // (crates/akribes-server/src/handlers/bench.rs / models.rs
    // ProjectBenchSummary): full row with a populated latest-run block.
    let _m = server
        .mock("GET", "/projects/7/benches")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"[{"bench_id":3,"script_id":11,"script_name":"summarise",
                "judge_script_id":12,"judge_script_name":"judge_quality",
                "judge_channel":"production","case_count":18,
                "latest_run_id":42,"latest_run_status":"completed",
                "latest_run_channel":"production","latest_run_workflow_version_id":99,
                "latest_run_at":"2026-01-02T00:00:00Z","latest_run_mean_score":0.91,
                "latest_run_cost_usd":0.42,"updated_at":"2026-01-02T00:00:00Z"}]"#,
        )
        .create_async()
        .await;
    let rows = bench(&server).list_project_summaries().await.unwrap();
    assert_eq!(rows.len(), 1);
    let r = &rows[0];
    assert_eq!(r.bench_id, 3);
    assert_eq!(r.script_name, "summarise");
    assert_eq!(r.judge_script_id, Some(12));
    assert_eq!(r.judge_script_name.as_deref(), Some("judge_quality"));
    assert_eq!(r.case_count, 18);
    assert_eq!(r.latest_run_id, Some(42));
    assert_eq!(r.latest_run_status.as_deref(), Some("completed"));
    assert_eq!(r.latest_run_mean_score, Some(0.91));
    assert_eq!(r.latest_run_cost_usd, Some(0.42));
}

#[tokio::test]
async fn list_project_summaries_tolerates_null_latest_run_block() {
    let mut server = Server::new_async().await;
    // A bench that has never been run leaves the entire latest-run block
    // NULL on the server (LEFT JOIN LATERAL miss). Every `latest_run_*`
    // field plus judge fields are `#[serde(default)]` Options, so the row
    // must still deserialise.
    let _m = server
        .mock("GET", "/projects/7/benches")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"[{"bench_id":4,"script_id":13,"script_name":"never_run",
                "judge_script_id":null,"judge_script_name":null,
                "judge_channel":"draft","case_count":0,
                "latest_run_id":null,"latest_run_status":null,
                "latest_run_channel":null,"latest_run_workflow_version_id":null,
                "latest_run_at":null,"latest_run_mean_score":null,
                "latest_run_cost_usd":null,"updated_at":"2026-01-02T00:00:00Z"}]"#,
        )
        .create_async()
        .await;
    let rows = bench(&server).list_project_summaries().await.unwrap();
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].script_name, "never_run");
    assert_eq!(rows[0].case_count, 0);
    assert!(rows[0].latest_run_id.is_none());
    assert!(rows[0].judge_script_id.is_none());
    assert_eq!(rows[0].judge_channel, "draft");
}

#[tokio::test]
async fn list_project_summaries_404_is_empty() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/projects/7/benches")
        .with_status(404)
        .create_async()
        .await;
    assert!(
        bench(&server)
            .list_project_summaries()
            .await
            .unwrap()
            .is_empty()
    );
}

// ── Bench config CRUD ────────────────────────────────────────────────────────

#[tokio::test]
async fn get_bench_hit() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/projects/7/scripts/summarise/bench")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"{"id":3,"script_id":11,"judge_script_id":12,"judge_channel":"production",
                "config":{"k":"v"},"created_at":"2026-01-01T00:00:00Z",
                "updated_at":"2026-01-02T00:00:00Z"}"#,
        )
        .create_async()
        .await;

    let got = bench(&server).get("summarise").await.unwrap();
    let b = got.expect("bench present");
    assert_eq!(b.id, 3);
    assert_eq!(b.script_id, 11);
    assert_eq!(b.judge_script_id, Some(12));
    assert_eq!(b.judge_channel, "production");
    assert_eq!(b.config["k"], "v");
}

#[tokio::test]
async fn get_bench_404_is_none() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/projects/7/scripts/nope/bench")
        .with_status(404)
        .create_async()
        .await;

    assert!(bench(&server).get("nope").await.unwrap().is_none());
}

#[tokio::test]
async fn create_or_update_bench_sends_only_set_fields() {
    let mut server = Server::new_async().await;
    // The SDK omits `None` fields via skip_serializing_if. A request that
    // only sets `judge_script_id` must NOT carry `judge_channel`/`config`
    // keys — the server defaults them, and an explicit `null` would change
    // behaviour. Assert exact body.
    let _m = server
        .mock("POST", "/projects/7/scripts/summarise/bench")
        .match_body(Matcher::Json(serde_json::json!({"judge_script_id": 12})))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"{"id":3,"script_id":11,"judge_script_id":12,"judge_channel":"draft",
                "config":{},"created_at":"2026-01-01T00:00:00Z",
                "updated_at":"2026-01-01T00:00:00Z"}"#,
        )
        .create_async()
        .await;

    let req = CreateOrUpdateBenchRequest {
        judge_script_id: Some(12),
        judge_channel: None,
        config: None,
    };
    let b = bench(&server)
        .create_or_update("summarise", &req)
        .await
        .unwrap();
    assert_eq!(b.judge_channel, "draft");
}

#[tokio::test]
async fn delete_bench_true_on_200() {
    let mut server = Server::new_async().await;
    // delete_bench returns 200 with `{"deleted":true}`, NOT 204. The SDK's
    // generic delete returns `status != 404` → true.
    let _m = server
        .mock("DELETE", "/projects/7/scripts/summarise/bench")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(r#"{"deleted":true}"#)
        .create_async()
        .await;
    assert!(bench(&server).delete("summarise").await.unwrap());
}

#[tokio::test]
async fn delete_bench_false_on_404() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("DELETE", "/projects/7/scripts/gone/bench")
        .with_status(404)
        .create_async()
        .await;
    assert!(!bench(&server).delete("gone").await.unwrap());
}

#[tokio::test]
async fn get_signature_maps_to_signature_route_not_bench() {
    let mut server = Server::new_async().await;
    // Regression guard: the signature endpoint is
    // `/projects/{id}/scripts/{name}/signature`, NOT under `/bench`.
    let _m = server
        .mock("GET", "/projects/7/scripts/summarise/signature")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(r#"{"inputs":[{"name":"q","type":"String"}]}"#)
        .create_async()
        .await;
    let sig = bench(&server).get_signature("summarise").await.unwrap();
    assert_eq!(sig["inputs"][0]["name"], "q");
}

#[tokio::test]
async fn get_signature_404_yields_empty_object() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/projects/7/scripts/x/signature")
        .with_status(404)
        .create_async()
        .await;
    let sig = bench(&server).get_signature("x").await.unwrap();
    assert_eq!(sig, serde_json::json!({}));
}

#[tokio::test]
async fn contract_preview_sends_judge_and_channel_query() {
    let mut server = Server::new_async().await;
    // judge is required; channel only present when Some.
    let _m = server
        .mock(
            "GET",
            "/projects/7/scripts/summarise/bench/contract-preview",
        )
        .match_query(Matcher::AllOf(vec![
            Matcher::UrlEncoded("judge".into(), "12".into()),
            Matcher::UrlEncoded("channel".into(), "production".into()),
        ]))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(r#"{"breaks":[]}"#)
        .create_async()
        .await;
    let prev = bench(&server)
        .contract_preview("summarise", 12, Some("production"))
        .await
        .unwrap();
    assert_eq!(prev["breaks"], serde_json::json!([]));
}

#[tokio::test]
async fn contract_preview_omits_channel_when_none() {
    let mut server = Server::new_async().await;
    // Exact full query: only `judge`, no `channel` key at all.
    let _m = server
        .mock(
            "GET",
            "/projects/7/scripts/summarise/bench/contract-preview",
        )
        .match_query(Matcher::Exact("judge=12".into()))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(r#"{"breaks":[]}"#)
        .create_async()
        .await;
    bench(&server)
        .contract_preview("summarise", 12, None)
        .await
        .unwrap();
}

// ── Cases ────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn list_cases_404_is_empty() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/projects/7/scripts/summarise/bench/cases")
        .with_status(404)
        .create_async()
        .await;
    assert!(
        bench(&server)
            .list_cases("summarise")
            .await
            .unwrap()
            .is_empty()
    );
}

#[tokio::test]
async fn list_cases_deserialises_rows() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/projects/7/scripts/summarise/bench/cases")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"[{"id":"case_a","project_id":7,"script_name":"summarise","bench_id":3,
                "kind":"case","frozen":true,"case_name":"happy",
                "inputs":{"q":"hi"},"expected_output":{"a":1},
                "created_at":"2026-01-01T00:00:00Z"}]"#,
        )
        .create_async()
        .await;
    let cases = bench(&server).list_cases("summarise").await.unwrap();
    assert_eq!(cases.len(), 1);
    assert_eq!(cases[0].id, "case_a");
    assert_eq!(cases[0].case_name.as_deref(), Some("happy"));
    assert!(cases[0].frozen);
    assert_eq!(cases[0].inputs.as_ref().unwrap()["q"], "hi");
}

#[tokio::test]
async fn create_case_sends_inputs_and_optional_fields() {
    let mut server = Server::new_async().await;
    // `inputs` is required and always serialised; expected_output present,
    // ground_truth/name omitted when None.
    let _m = server
        .mock("POST", "/projects/7/scripts/summarise/bench/cases")
        .match_body(Matcher::Json(serde_json::json!({
            "inputs": {"q": "hi"},
            "expected_output": {"a": 1},
        })))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"{"id":"case_new","project_id":7,"script_name":"summarise","kind":"case",
                "frozen":true,"created_at":"2026-01-01T00:00:00Z"}"#,
        )
        .create_async()
        .await;
    let req = CreateBenchCaseRequest {
        inputs: serde_json::json!({"q": "hi"}),
        expected_output: Some(serde_json::json!({"a": 1})),
        ground_truth: None,
        name: None,
    };
    let case = bench(&server).create_case("summarise", &req).await.unwrap();
    assert_eq!(case.id, "case_new");
}

#[tokio::test]
async fn case_contract_drift_404_yields_empty_report() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock(
            "GET",
            "/projects/7/scripts/summarise/bench/cases/contract-drift",
        )
        .with_status(404)
        .create_async()
        .await;
    let report = bench(&server)
        .case_contract_drift("summarise")
        .await
        .unwrap();
    assert!(report.drifted.is_empty());
    assert_eq!(report.summary, "");
}

#[tokio::test]
async fn case_contract_drift_parses_drifted_rows() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock(
            "GET",
            "/projects/7/scripts/summarise/bench/cases/contract-drift",
        )
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"{"drifted":[{"case_id":"case_a","label":"happy",
                "what_broke":"outputs.score removed"}],
                "script_version_id":99,"published_at":"2026-01-01T00:00:00Z",
                "published_by":"alice","summary":"1 case drifted"}"#,
        )
        .create_async()
        .await;
    let report = bench(&server)
        .case_contract_drift("summarise")
        .await
        .unwrap();
    assert_eq!(report.drifted.len(), 1);
    assert_eq!(report.drifted[0].case_id, "case_a");
    assert_eq!(report.drifted[0].what_broke, "outputs.score removed");
    assert_eq!(report.script_version_id, Some(99));
    assert_eq!(report.summary, "1 case drifted");
}

// ── Runs (project-scoped) ────────────────────────────────────────────────────

#[tokio::test]
async fn list_runs_sends_limit_offset_query() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/projects/7/scripts/summarise/bench/runs")
        .match_query(Matcher::AllOf(vec![
            Matcher::UrlEncoded("limit".into(), "5".into()),
            Matcher::UrlEncoded("offset".into(), "10".into()),
        ]))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"[{"id":1,"bench_id":3,"channel":"production","workflow_version_id":99,
                "judge_version_id":100,"status":"completed","triggered_at":"2026-01-01T00:00:00Z",
                "mean_headline_score":0.91,"ok_cases":7}]"#,
        )
        .create_async()
        .await;
    let runs = bench(&server)
        .list_runs("summarise", Some(5), Some(10))
        .await
        .unwrap();
    assert_eq!(runs.len(), 1);
    assert_eq!(runs[0].id, 1);
    assert_eq!(runs[0].mean_headline_score, Some(0.91));
    assert_eq!(runs[0].ok_cases, Some(7));
}

#[tokio::test]
async fn list_runs_omits_query_when_no_pagination() {
    let mut server = Server::new_async().await;
    // Both None → no query string at all (the helper returns the bare base
    // URL). A stray `?limit=&offset=` would change the server's parse.
    let _m = server
        .mock("GET", "/projects/7/scripts/summarise/bench/runs")
        .match_query(Matcher::Missing)
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body("[]")
        .create_async()
        .await;
    let runs = bench(&server)
        .list_runs("summarise", None, None)
        .await
        .unwrap();
    assert!(runs.is_empty());
}

#[tokio::test]
async fn trigger_run_sends_channel_required_and_case_ids() {
    let mut server = Server::new_async().await;
    // channel is non-optional; case_ids present, notes omitted when None.
    let _m = server
        .mock("POST", "/projects/7/scripts/summarise/bench/runs")
        .match_body(Matcher::Json(serde_json::json!({
            "channel": "production",
            "case_ids": ["case_a", "case_b"],
        })))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"{"id":42,"bench_id":3,"channel":"production","workflow_version_id":99,
                "judge_version_id":100,"status":"pending","triggered_at":"2026-01-01T00:00:00Z"}"#,
        )
        .create_async()
        .await;
    let req = TriggerBenchRunRequest {
        channel: "production".into(),
        notes: None,
        case_ids: Some(vec!["case_a".into(), "case_b".into()]),
    };
    let run = bench(&server).trigger_run("summarise", &req).await.unwrap();
    assert_eq!(run.id, 42);
    assert_eq!(run.status, "pending");
}

// ── Run-scoped (cross-project) ───────────────────────────────────────────────

#[tokio::test]
async fn run_get_404_is_none() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/bench-runs/42")
        .with_status(404)
        .create_async()
        .await;
    assert!(runs(&server).get(42).await.unwrap().is_none());
}

#[tokio::test]
async fn run_delete_succeeds_on_204() {
    let mut server = Server::new_async().await;
    // The server emits 204 No Content; the SDK discards the bool → Ok(()).
    let _m = server
        .mock("DELETE", "/bench-runs/42")
        .with_status(204)
        .create_async()
        .await;
    runs(&server).delete(42).await.unwrap();
}

#[tokio::test]
async fn list_results_deserialises() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/bench-runs/42/results")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"[{"id":1,"bench_run_id":42,"case_id":"case_a","headline_score":0.8,
                "status":"ok","created_at":"2026-01-01T00:00:00Z"}]"#,
        )
        .create_async()
        .await;
    let results = runs(&server).list_results(42).await.unwrap();
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].case_id, "case_a");
    assert_eq!(results[0].headline_score, Some(0.8));
    assert_eq!(results[0].status, "ok");
}

#[tokio::test]
async fn cancel_posts_empty_body_and_returns_run() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("POST", "/bench-runs/42/cancel")
        .match_body(Matcher::Json(serde_json::json!({})))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"{"id":42,"bench_id":3,"channel":"production","workflow_version_id":99,
                "judge_version_id":100,"status":"canceled","triggered_at":"2026-01-01T00:00:00Z"}"#,
        )
        .create_async()
        .await;
    let run = runs(&server).cancel(42).await.unwrap();
    assert_eq!(run.status, "canceled");
}

#[tokio::test]
async fn tag_session_patches_with_mcp_session_id() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("PATCH", "/bench-runs/42/tag-session")
        .match_body(Matcher::Json(serde_json::json!({
            "mcp_session_id": "sess_abc"
        })))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(r#"{"tagged":true,"run_id":42,"mcp_session_id":"sess_abc"}"#)
        .create_async()
        .await;
    let resp = runs(&server).tag_session(42, "sess_abc").await.unwrap();
    assert!(resp.tagged);
    assert_eq!(resp.run_id, 42);
    assert_eq!(resp.mcp_session_id, "sess_abc");
}

#[tokio::test]
async fn promote_execution_posts_edits_overlay() {
    let mut server = Server::new_async().await;
    // promote-to-case lives on /executions/{id}, NOT /bench-runs.
    let _m = server
        .mock("POST", "/executions/exec_123/promote-to-case")
        .match_body(Matcher::Json(serde_json::json!({
            "edits": {"expected_output": {"a": 2}},
            "name": "T_1",
        })))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"{"id":"case_p","project_id":7,"script_name":"summarise","kind":"case",
                "frozen":true,"case_name":"T_1","created_at":"2026-01-01T00:00:00Z"}"#,
        )
        .create_async()
        .await;
    let req = PromoteExecutionRequest {
        edits: Some(PromoteCaseEdits {
            inputs: None,
            expected_output: Some(serde_json::json!({"a": 2})),
            ground_truth: None,
        }),
        name: Some("T_1".into()),
    };
    let case = runs(&server)
        .promote_execution("exec_123", &req)
        .await
        .unwrap();
    assert_eq!(case.id, "case_p");
    assert_eq!(case.case_name.as_deref(), Some("T_1"));
}

#[tokio::test]
async fn promote_execution_url_encodes_exec_id() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("POST", "/executions/exec%2F123/promote-to-case")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"{"id":"c","project_id":7,"script_name":"s","kind":"case","frozen":true,
                "created_at":"2026-01-01T00:00:00Z"}"#,
        )
        .create_async()
        .await;
    runs(&server)
        .promote_execution("exec/123", &PromoteExecutionRequest::default())
        .await
        .unwrap();
}

#[tokio::test]
async fn compare_parses_aggregate_and_per_case() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/bench-runs/10/compare/20")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"{"run_a_id":10,"run_b_id":20,
                "aggregate":{"mean_score_delta":0.05,"cost_delta_usd":-0.1,
                    "n_regressed":1,"n_improved":3,"n_unchanged":2},
                "per_case":[{"case_id":"case_a","case_label":"happy","score_a":0.8,
                    "score_b":0.9,"delta":0.1,"flag":"improved"}]}"#,
        )
        .create_async()
        .await;
    let report = runs(&server).compare(10, 20).await.unwrap();
    assert_eq!(report.run_a_id, 10);
    assert_eq!(report.aggregate.n_improved, 3);
    assert_eq!(report.per_case.len(), 1);
    assert_eq!(report.per_case[0].flag, "improved");
    assert_eq!(report.per_case[0].delta, Some(0.1));
}

#[tokio::test]
async fn compare_404_surfaces_http_status() {
    let mut server = Server::new_async().await;
    // compare uses get_opt then maps None→HttpStatus 404 (not a silent
    // empty report) because there's no meaningful empty comparison.
    let _m = server
        .mock("GET", "/bench-runs/10/compare/20")
        .with_status(404)
        .create_async()
        .await;
    let err = runs(&server).compare(10, 20).await.unwrap_err();
    match err {
        AkribesError::HttpStatus { status, .. } => assert_eq!(status, 404),
        other => panic!("expected HttpStatus 404, got {other:?}"),
    }
}

#[tokio::test]
async fn patch_case_sends_sparse_update() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("PATCH", "/cases/case_a")
        .match_body(Matcher::Json(serde_json::json!({"name": "renamed"})))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            r#"{"id":"case_a","project_id":7,"script_name":"s","kind":"case","frozen":true,
                "case_name":"renamed","created_at":"2026-01-01T00:00:00Z"}"#,
        )
        .create_async()
        .await;
    let req = PatchBenchCaseRequest {
        name: Some("renamed".into()),
        ..Default::default()
    };
    let case = runs(&server).patch_case("case_a", &req).await.unwrap();
    assert_eq!(case.case_name.as_deref(), Some("renamed"));
}

#[tokio::test]
async fn delete_case_succeeds() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("DELETE", "/cases/case_a")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(r#"{"deleted":true}"#)
        .create_async()
        .await;
    runs(&server).delete_case("case_a").await.unwrap();
}

#[tokio::test]
async fn get_case_404_yields_null_value() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/executions/case_a")
        .with_status(404)
        .create_async()
        .await;
    let v = runs(&server).get_case("case_a").await.unwrap();
    assert_eq!(v, serde_json::Value::Null);
}

#[tokio::test]
async fn bench_by_id_404_is_none() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/benches/5")
        .with_status(404)
        .create_async()
        .await;
    assert!(runs(&server).bench_by_id(5).await.unwrap().is_none());
}

#[tokio::test]
async fn bench_by_id_returns_value() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/benches/5")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(r#"{"id":5,"project_id":7,"script_name":"summarise"}"#)
        .create_async()
        .await;
    let v = runs(&server).bench_by_id(5).await.unwrap().unwrap();
    assert_eq!(v["script_name"], "summarise");
}

#[tokio::test]
async fn mcp_session_cost_returns_value() {
    let mut server = Server::new_async().await;
    let _m = server
        .mock("GET", "/mcp-sessions/sess_abc/cost")
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(r#"{"session_id":"sess_abc","total_cost_usd":1.25,"breakdown":[]}"#)
        .create_async()
        .await;
    let v = runs(&server).mcp_session_cost("sess_abc").await.unwrap();
    assert_eq!(v["total_cost_usd"], 1.25);
}