runcycles 0.2.4

Runtime authority for AI agents in Rust — hard limits on agent spend, risky tool actions, and audit gaps. Tokio-native client for the Cycles protocol (reserve-commit lifecycle, RAII guards).
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
//! Integration tests for CyclesClient using wiremock.

use runcycles::models::*;
use runcycles::{CyclesClient, Error};
use serde_json::json;
use wiremock::matchers::{header, method, path, path_regex};
use wiremock::{Mock, MockServer, ResponseTemplate};

async fn setup() -> (MockServer, CyclesClient) {
    let server = MockServer::start().await;
    let client = CyclesClient::builder("test-api-key", server.uri()).build();
    (server, client)
}

// ─── create_reservation ───────────────────────────────────────────

#[tokio::test]
async fn create_reservation_success() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations"))
        .and(header("X-Cycles-API-Key", "test-api-key"))
        .and(header("Content-Type", "application/json"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "decision": "ALLOW",
            "reservation_id": "rsv_123",
            "affected_scopes": ["tenant:acme"],
            "expires_at_ms": 1700000000000_u64,
            "scope_path": "tenant:acme",
            "reserved": {"unit": "USD_MICROCENTS", "amount": 5000},
            "caps": null,
            "reason_code": null,
            "retry_after_ms": null,
            "balances": null
        })))
        .expect(1)
        .mount(&server)
        .await;

    let req = ReservationCreateRequest::builder()
        .subject(Subject {
            tenant: Some("acme".into()),
            ..Default::default()
        })
        .action(Action::new("llm.completion", "gpt-4o"))
        .estimate(Amount::usd_microcents(5000))
        .build();

    let resp = client.create_reservation(&req).await.unwrap();
    assert_eq!(resp.decision, Decision::Allow);
    assert_eq!(resp.reservation_id.unwrap().as_str(), "rsv_123");
    assert_eq!(resp.affected_scopes, vec!["tenant:acme"]);
}

#[tokio::test]
async fn create_reservation_allow_with_caps() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "decision": "ALLOW_WITH_CAPS",
            "reservation_id": "rsv_456",
            "affected_scopes": ["tenant:acme"],
            "caps": {
                "max_tokens": 100,
                "tool_allowlist": ["web_search"]
            }
        })))
        .mount(&server)
        .await;

    let req = ReservationCreateRequest::builder()
        .subject(Subject {
            tenant: Some("acme".into()),
            ..Default::default()
        })
        .action(Action::new("llm.completion", "gpt-4o"))
        .estimate(Amount::usd_microcents(5000))
        .build();

    let resp = client.create_reservation(&req).await.unwrap();
    assert_eq!(resp.decision, Decision::AllowWithCaps);
    let caps = resp.caps.unwrap();
    assert_eq!(caps.max_tokens, Some(100));
    assert!(caps.is_tool_allowed("web_search"));
    assert!(!caps.is_tool_allowed("code_exec"));
}

#[tokio::test]
async fn create_reservation_with_metadata_has_headers() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({
                    "decision": "ALLOW",
                    "reservation_id": "rsv_789",
                    "affected_scopes": []
                }))
                .append_header("x-request-id", "req-abc-123")
                .append_header("x-ratelimit-remaining", "99")
                .append_header("x-ratelimit-reset", "1700000000")
                .append_header("x-cycles-tenant", "acme"),
        )
        .mount(&server)
        .await;

    let req = ReservationCreateRequest::builder()
        .subject(Subject {
            tenant: Some("acme".into()),
            ..Default::default()
        })
        .action(Action::new("llm.completion", "gpt-4o"))
        .estimate(Amount::usd_microcents(5000))
        .build();

    let resp = client.create_reservation_with_metadata(&req).await.unwrap();
    assert_eq!(resp.request_id.as_deref(), Some("req-abc-123"));
    assert_eq!(resp.rate_limit_remaining, Some(99));
    assert_eq!(resp.rate_limit_reset, Some(1700000000));
    assert_eq!(resp.cycles_tenant.as_deref(), Some("acme"));
    assert_eq!(resp.data.decision, Decision::Allow);

    // Deref works
    assert_eq!(resp.decision, Decision::Allow);
}

#[tokio::test]
async fn create_reservation_budget_exceeded() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations"))
        .respond_with(ResponseTemplate::new(409).set_body_json(json!({
            "error": "BUDGET_EXCEEDED",
            "message": "Insufficient budget for tenant:acme",
            "request_id": "req-err-1"
        })))
        .mount(&server)
        .await;

    let req = ReservationCreateRequest::builder()
        .subject(Subject {
            tenant: Some("acme".into()),
            ..Default::default()
        })
        .action(Action::new("llm.completion", "gpt-4o"))
        .estimate(Amount::usd_microcents(999999))
        .build();

    let err = client.create_reservation(&req).await.unwrap_err();
    assert!(err.is_budget_exceeded());
    assert_eq!(err.request_id(), Some("req-err-1"));
}

#[tokio::test]
async fn create_reservation_server_error() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations"))
        .respond_with(ResponseTemplate::new(500).set_body_json(json!({
            "error": "INTERNAL_ERROR",
            "message": "Something went wrong",
            "request_id": "req-500"
        })))
        .mount(&server)
        .await;

    let req = ReservationCreateRequest::builder()
        .subject(Subject {
            tenant: Some("acme".into()),
            ..Default::default()
        })
        .action(Action::new("llm.completion", "gpt-4o"))
        .estimate(Amount::usd_microcents(5000))
        .build();

    let err = client.create_reservation(&req).await.unwrap_err();
    assert!(err.is_retryable());
    assert_eq!(err.error_code(), Some(ErrorCode::InternalError));
}

// ─── commit_reservation ───────────────────────────────────────────

#[tokio::test]
async fn commit_reservation_success() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations/rsv_123/commit"))
        .and(header("X-Cycles-API-Key", "test-api-key"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "COMMITTED",
            "charged": {"unit": "USD_MICROCENTS", "amount": 3200},
            "released": {"unit": "USD_MICROCENTS", "amount": 1800}
        })))
        .mount(&server)
        .await;

    let id = ReservationId::new("rsv_123");
    let req = CommitRequest::builder()
        .actual(Amount::usd_microcents(3200))
        .build();

    let resp = client.commit_reservation(&id, &req).await.unwrap();
    assert_eq!(resp.status, CommitStatus::Committed);
    assert_eq!(resp.charged.amount, 3200);
    assert_eq!(resp.released.unwrap().amount, 1800);
}

#[tokio::test]
async fn commit_with_metrics() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations/rsv_m/commit"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "COMMITTED",
            "charged": {"unit": "TOKENS", "amount": 300}
        })))
        .mount(&server)
        .await;

    let id = ReservationId::new("rsv_m");
    let req = CommitRequest::builder()
        .actual(Amount::tokens(300))
        .metrics(CyclesMetrics {
            tokens_input: Some(100),
            tokens_output: Some(200),
            latency_ms: Some(1500),
            model_version: Some("gpt-4o-2024-05".to_string()),
            ..Default::default()
        })
        .build();

    let resp = client.commit_reservation(&id, &req).await.unwrap();
    assert_eq!(resp.charged.unit, Unit::Tokens);
    assert_eq!(resp.charged.amount, 300);
}

// ─── release_reservation ──────────────────────────────────────────

#[tokio::test]
async fn release_reservation_success() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations/rsv_rel/release"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "RELEASED",
            "released": {"unit": "USD_MICROCENTS", "amount": 5000}
        })))
        .mount(&server)
        .await;

    let id = ReservationId::new("rsv_rel");
    let req = ReleaseRequest::new(Some("user_cancelled".to_string()));

    let resp = client.release_reservation(&id, &req).await.unwrap();
    assert_eq!(resp.status, ReleaseStatus::Released);
    assert_eq!(resp.released.amount, 5000);
}

// ─── extend_reservation ──────────────────────────────────────────

#[tokio::test]
async fn extend_reservation_success() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations/rsv_ext/extend"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "ACTIVE",
            "expires_at_ms": 1700000060000_u64
        })))
        .mount(&server)
        .await;

    let id = ReservationId::new("rsv_ext");
    let req = ExtendRequest::new(60_000);

    let resp = client.extend_reservation(&id, &req).await.unwrap();
    assert_eq!(resp.status, ExtendStatus::Active);
    assert_eq!(resp.expires_at_ms, 1700000060000);
}

// ─── decide ──────────────────────────────────────────────────────

#[tokio::test]
async fn decide_allow() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/decide"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "decision": "ALLOW"
        })))
        .mount(&server)
        .await;

    let req = DecisionRequest::builder()
        .subject(Subject {
            tenant: Some("acme".into()),
            ..Default::default()
        })
        .action(Action::new("llm.completion", "gpt-4o"))
        .estimate(Amount::usd_microcents(5000))
        .build();

    let resp = client.decide(&req).await.unwrap();
    assert_eq!(resp.decision, Decision::Allow);
    assert!(resp.caps.is_none());
}

#[tokio::test]
async fn decide_deny() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/decide"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "decision": "DENY",
            "reason_code": "DEBT_OUTSTANDING",
            "retry_after_ms": 5000
        })))
        .mount(&server)
        .await;

    let req = DecisionRequest::builder()
        .subject(Subject {
            tenant: Some("acme".into()),
            ..Default::default()
        })
        .action(Action::new("llm.completion", "gpt-4o"))
        .estimate(Amount::usd_microcents(5000))
        .build();

    let resp = client.decide(&req).await.unwrap();
    assert!(resp.decision.is_denied());
    assert_eq!(resp.reason_code.as_deref(), Some("DEBT_OUTSTANDING"));
    assert_eq!(resp.retry_after_ms, Some(5000));
}

// ─── create_event ────────────────────────────────────────────────

#[tokio::test]
async fn create_event_success() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/events"))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({
            "status": "APPLIED",
            "event_id": "evt_001",
            "charged": {"unit": "USD_MICROCENTS", "amount": 1500}
        })))
        .mount(&server)
        .await;

    let req = EventCreateRequest::builder()
        .subject(Subject {
            tenant: Some("acme".into()),
            ..Default::default()
        })
        .action(Action::new("tool.search", "web_search"))
        .actual(Amount::usd_microcents(1500))
        .build();

    let resp = client.create_event(&req).await.unwrap();
    assert_eq!(resp.status, EventStatus::Applied);
    assert_eq!(resp.event_id.as_str(), "evt_001");
    assert_eq!(resp.charged.unwrap().amount, 1500);
}

// ─── list_reservations ──────────────────────────────────────────

#[tokio::test]
async fn list_reservations_success() {
    let (server, client) = setup().await;

    Mock::given(method("GET"))
        .and(path("/v1/reservations"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "reservations": [
                {
                    "reservation_id": "rsv_1",
                    "status": "ACTIVE",
                    "subject": {"tenant": "acme"},
                    "action": {"kind": "llm.completion", "name": "gpt-4o"},
                    "reserved": {"unit": "USD_MICROCENTS", "amount": 5000},
                    "created_at_ms": 1700000000000_u64,
                    "expires_at_ms": 1700000060000_u64,
                    "scope_path": "tenant:acme",
                    "affected_scopes": ["tenant:acme"]
                }
            ],
            "has_more": false
        })))
        .mount(&server)
        .await;

    let params = ListReservationsParams::default();
    let resp = client.list_reservations(&params).await.unwrap();
    assert_eq!(resp.reservations.len(), 1);
    assert_eq!(resp.reservations[0].reservation_id.as_str(), "rsv_1");
    assert_eq!(resp.reservations[0].status, ReservationStatus::Active);
    assert_eq!(resp.has_more, Some(false));
}

// ─── get_reservation ─────────────────────────────────────────────

#[tokio::test]
async fn get_reservation_success() {
    let (server, client) = setup().await;

    Mock::given(method("GET"))
        .and(path("/v1/reservations/rsv_detail"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "reservation_id": "rsv_detail",
            "status": "COMMITTED",
            "subject": {"tenant": "acme"},
            "action": {"kind": "llm.completion", "name": "gpt-4o"},
            "reserved": {"unit": "USD_MICROCENTS", "amount": 5000},
            "committed": {"unit": "USD_MICROCENTS", "amount": 3200},
            "created_at_ms": 1700000000000_u64,
            "expires_at_ms": 1700000060000_u64,
            "finalized_at_ms": 1700000030000_u64,
            "scope_path": "tenant:acme",
            "affected_scopes": ["tenant:acme"]
        })))
        .mount(&server)
        .await;

    let id = ReservationId::new("rsv_detail");
    let resp = client.get_reservation(&id).await.unwrap();
    assert_eq!(resp.status, ReservationStatus::Committed);
    assert_eq!(resp.committed.unwrap().amount, 3200);
    assert_eq!(resp.finalized_at_ms, Some(1700000030000));
}

// ─── get_balances ────────────────────────────────────────────────

#[tokio::test]
async fn get_balances_success() {
    let (server, client) = setup().await;

    Mock::given(method("GET"))
        .and(path("/v1/balances"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "balances": [
                {
                    "scope": "tenant:acme",
                    "scope_path": "tenant:acme",
                    "remaining": {"unit": "USD_MICROCENTS", "amount": 50000},
                    "reserved": {"unit": "USD_MICROCENTS", "amount": 5000},
                    "spent": {"unit": "USD_MICROCENTS", "amount": 10000},
                    "allocated": {"unit": "USD_MICROCENTS", "amount": 65000},
                    "is_over_limit": false
                }
            ]
        })))
        .mount(&server)
        .await;

    let params = BalanceParams {
        tenant: Some("acme".into()),
        ..Default::default()
    };

    let resp = client.get_balances(&params).await.unwrap();
    assert_eq!(resp.balances.len(), 1);
    assert_eq!(resp.balances[0].scope, "tenant:acme");
    assert_eq!(resp.balances[0].remaining.amount, 50000);
    assert_eq!(resp.balances[0].is_over_limit, Some(false));
}

#[tokio::test]
async fn get_balances_requires_filter() {
    let (_server, client) = setup().await;
    let params = BalanceParams::default();
    let err = client.get_balances(&params).await.unwrap_err();
    match err {
        Error::Validation(msg) => {
            assert!(msg.contains("filter"));
        }
        _ => panic!("expected Validation error, got {:?}", err),
    }
}

// ─── reserve (high-level) ────────────────────────────────────────

#[tokio::test]
async fn reserve_returns_guard_on_allow() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "decision": "ALLOW",
            "reservation_id": "rsv_guard",
            "affected_scopes": ["tenant:acme"],
            "expires_at_ms": 1700000060000_u64
        })))
        .mount(&server)
        .await;

    // Also mock extend for heartbeat and release for guard drop
    Mock::given(method("POST"))
        .and(path_regex("/v1/reservations/rsv_guard/(extend|release)"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "ACTIVE",
            "expires_at_ms": 1700000120000_u64
        })))
        .mount(&server)
        .await;

    let guard = client
        .reserve(
            ReservationCreateRequest::builder()
                .subject(Subject {
                    tenant: Some("acme".into()),
                    ..Default::default()
                })
                .action(Action::new("llm.completion", "gpt-4o"))
                .estimate(Amount::usd_microcents(5000))
                .build(),
        )
        .await
        .unwrap();

    assert_eq!(guard.reservation_id().as_str(), "rsv_guard");
    assert_eq!(guard.decision(), Decision::Allow);
    assert!(guard.caps().is_none());
    assert!(!guard.is_capped());
    assert_eq!(guard.affected_scopes(), &["tenant:acme"]);
    assert_eq!(guard.expires_at_ms(), Some(1700000060000));

    // Drop triggers release
    drop(guard);
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}

#[tokio::test]
async fn reserve_returns_error_on_deny() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "decision": "DENY",
            "affected_scopes": ["tenant:acme"],
            "reason_code": "BUDGET_EXCEEDED",
            "retry_after_ms": 10000
        })))
        .mount(&server)
        .await;

    let err = client
        .reserve(
            ReservationCreateRequest::builder()
                .subject(Subject {
                    tenant: Some("acme".into()),
                    ..Default::default()
                })
                .action(Action::new("llm.completion", "gpt-4o"))
                .estimate(Amount::usd_microcents(999999))
                .build(),
        )
        .await
        .unwrap_err();

    assert!(err.is_budget_exceeded());
}

#[tokio::test]
async fn reserve_validates_subject() {
    let (_server, client) = setup().await;

    let err = client
        .reserve(
            ReservationCreateRequest::builder()
                .subject(Subject::default()) // no fields set
                .action(Action::new("llm.completion", "gpt-4o"))
                .estimate(Amount::usd_microcents(5000))
                .build(),
        )
        .await
        .unwrap_err();

    match err {
        Error::Validation(msg) => assert!(msg.contains("Subject")),
        _ => panic!("expected Validation error"),
    }
}

#[tokio::test]
async fn reserve_validates_ttl() {
    let (_server, client) = setup().await;

    let err = client
        .reserve(
            ReservationCreateRequest::builder()
                .subject(Subject {
                    tenant: Some("acme".into()),
                    ..Default::default()
                })
                .action(Action::new("llm.completion", "gpt-4o"))
                .estimate(Amount::usd_microcents(5000))
                .ttl_ms(500_u64) // too low
                .build(),
        )
        .await
        .unwrap_err();

    match err {
        Error::Validation(msg) => assert!(msg.contains("ttl_ms")),
        _ => panic!("expected Validation error"),
    }
}

#[tokio::test]
async fn reserve_validates_negative_estimate() {
    let (_server, client) = setup().await;

    let err = client
        .reserve(
            ReservationCreateRequest::builder()
                .subject(Subject {
                    tenant: Some("acme".into()),
                    ..Default::default()
                })
                .action(Action::new("llm.completion", "gpt-4o"))
                .estimate(Amount::usd_microcents(-1))
                .build(),
        )
        .await
        .unwrap_err();

    match err {
        Error::Validation(msg) => assert!(msg.contains("non-negative")),
        _ => panic!("expected Validation error"),
    }
}

// ─── guard commit and release ────────────────────────────────────

#[tokio::test]
async fn guard_commit_success() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "decision": "ALLOW",
            "reservation_id": "rsv_gc",
            "affected_scopes": ["tenant:acme"]
        })))
        .mount(&server)
        .await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations/rsv_gc/commit"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "COMMITTED",
            "charged": {"unit": "USD_MICROCENTS", "amount": 3200}
        })))
        .mount(&server)
        .await;

    // Mock extend for heartbeat
    Mock::given(method("POST"))
        .and(path("/v1/reservations/rsv_gc/extend"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "ACTIVE",
            "expires_at_ms": 1700000120000_u64
        })))
        .mount(&server)
        .await;

    let guard = client
        .reserve(
            ReservationCreateRequest::builder()
                .subject(Subject {
                    tenant: Some("acme".into()),
                    ..Default::default()
                })
                .action(Action::new("llm.completion", "gpt-4o"))
                .estimate(Amount::usd_microcents(5000))
                .build(),
        )
        .await
        .unwrap();

    let resp = guard
        .commit(
            CommitRequest::builder()
                .actual(Amount::usd_microcents(3200))
                .build(),
        )
        .await
        .unwrap();

    assert_eq!(resp.status, CommitStatus::Committed);
    assert_eq!(resp.charged.amount, 3200);
}

#[tokio::test]
async fn guard_release_success() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "decision": "ALLOW",
            "reservation_id": "rsv_gr",
            "affected_scopes": ["tenant:acme"]
        })))
        .mount(&server)
        .await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations/rsv_gr/release"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "RELEASED",
            "released": {"unit": "USD_MICROCENTS", "amount": 5000}
        })))
        .mount(&server)
        .await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations/rsv_gr/extend"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "status": "ACTIVE",
            "expires_at_ms": 1700000120000_u64
        })))
        .mount(&server)
        .await;

    let guard = client
        .reserve(
            ReservationCreateRequest::builder()
                .subject(Subject {
                    tenant: Some("acme".into()),
                    ..Default::default()
                })
                .action(Action::new("llm.completion", "gpt-4o"))
                .estimate(Amount::usd_microcents(5000))
                .build(),
        )
        .await
        .unwrap();

    let resp = guard.release("user_cancelled").await.unwrap();
    assert_eq!(resp.status, ReleaseStatus::Released);
}

// ─── transport error ──────────────────────────────────────────────

#[tokio::test]
async fn transport_error_on_bad_url() {
    let client = CyclesClient::builder("test-key", "http://127.0.0.1:1")
        .connect_timeout(std::time::Duration::from_millis(100))
        .build();

    let req = ReservationCreateRequest::builder()
        .subject(Subject {
            tenant: Some("acme".into()),
            ..Default::default()
        })
        .action(Action::new("llm.completion", "gpt-4o"))
        .estimate(Amount::usd_microcents(5000))
        .build();

    let err = client.create_reservation(&req).await.unwrap_err();
    assert!(matches!(err, Error::Transport(_)));
    assert!(err.is_retryable());
}

// ─── idempotency key header ──────────────────────────────────────

#[tokio::test]
async fn idempotency_key_sent_as_header() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations"))
        .and(header("X-Idempotency-Key", "my-idem-key"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "decision": "ALLOW",
            "reservation_id": "rsv_idem",
            "affected_scopes": []
        })))
        .expect(1)
        .mount(&server)
        .await;

    let req = ReservationCreateRequest::builder()
        .idempotency_key(IdempotencyKey::new("my-idem-key"))
        .subject(Subject {
            tenant: Some("acme".into()),
            ..Default::default()
        })
        .action(Action::new("llm.completion", "gpt-4o"))
        .estimate(Amount::usd_microcents(5000))
        .build();

    client.create_reservation(&req).await.unwrap();
}

// ─── unknown error code handling ─────────────────────────────────

#[tokio::test]
async fn unknown_error_code_does_not_crash() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations"))
        .respond_with(ResponseTemplate::new(422).set_body_json(json!({
            "error": "SOME_FUTURE_ERROR",
            "message": "A new error type",
            "request_id": "req-future"
        })))
        .mount(&server)
        .await;

    let req = ReservationCreateRequest::builder()
        .subject(Subject {
            tenant: Some("acme".into()),
            ..Default::default()
        })
        .action(Action::new("llm.completion", "gpt-4o"))
        .estimate(Amount::usd_microcents(5000))
        .build();

    let err = client.create_reservation(&req).await.unwrap_err();
    match err {
        Error::Api { code, message, .. } => {
            assert_eq!(code, Some(ErrorCode::Unknown));
            assert_eq!(message, "A new error type");
        }
        _ => panic!("expected Api error"),
    }
}

// ─── 404 unit-mismatch diagnostic (issue #8) ──────────────────────

/// When the server stores a budget at (scope=tenant:rider, unit=USD_MICROCENTS)
/// but a reservation is sent in a different unit, the Lua script in
/// `reserve.lua` reports `BUDGET_NOT_FOUND` because it indexes budgets by
/// (scope, unit). The raw 404 message ("Budget not found for provided scope:
/// tenant:rider") is misleading. The Rust client enriches it in-flight so the
/// user sees which unit was actually sent.
#[tokio::test]
async fn create_reservation_404_budget_not_found_is_enriched_with_unit() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations"))
        .respond_with(ResponseTemplate::new(404).set_body_json(json!({
            "error": "NOT_FOUND",
            "message": "Budget not found for provided scope: tenant:rider",
            "request_id": "req-abc-123"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let req = ReservationCreateRequest::builder()
        .subject(Subject {
            tenant: Some("rider".into()),
            ..Default::default()
        })
        .action(Action::new("llm.completion", "gpt-4o"))
        .estimate(Amount::tokens(1000))
        .build();

    let err = client.create_reservation(&req).await.unwrap_err();
    match err {
        Error::Api {
            status,
            code,
            message,
            request_id,
            ..
        } => {
            assert_eq!(status, 404);
            assert_eq!(code, Some(ErrorCode::NotFound));
            assert!(message.starts_with("Budget not found for provided scope: tenant:rider"));
            assert!(
                message.contains("unit=TOKENS"),
                "expected enriched message to name the sent unit, got: {message}"
            );
            assert!(message.contains("(scope, unit)"));
            assert_eq!(request_id.as_deref(), Some("req-abc-123"));
        }
        other => panic!("expected Api error, got {other:?}"),
    }
}

#[tokio::test]
async fn decide_404_budget_not_found_is_enriched_with_unit() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/decide"))
        .respond_with(ResponseTemplate::new(404).set_body_json(json!({
            "error": "NOT_FOUND",
            "message": "Budget not found for provided scope: tenant:acme"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let req = DecisionRequest::builder()
        .subject(Subject {
            tenant: Some("acme".into()),
            ..Default::default()
        })
        .action(Action::new("llm.completion", "gpt-4o"))
        .estimate(Amount::credits(10))
        .build();

    let err = client.decide(&req).await.unwrap_err();
    match err {
        Error::Api { message, .. } => {
            assert!(message.contains("unit=CREDITS"));
        }
        other => panic!("expected Api error, got {other:?}"),
    }
}

#[tokio::test]
async fn create_event_404_budget_not_found_is_enriched_with_unit() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/events"))
        .respond_with(ResponseTemplate::new(404).set_body_json(json!({
            "error": "NOT_FOUND",
            "message": "Budget not found for provided scope: tenant:acme"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let req = EventCreateRequest::builder()
        .subject(Subject {
            tenant: Some("acme".into()),
            ..Default::default()
        })
        .action(Action::new("llm.completion", "gpt-4o"))
        .actual(Amount::risk_points(5))
        .build();

    let err = client.create_event(&req).await.unwrap_err();
    match err {
        Error::Api { message, .. } => {
            assert!(message.contains("unit=RISK_POINTS"));
        }
        other => panic!("expected Api error, got {other:?}"),
    }
}

/// An unrelated 404 (e.g. a missing reservation path) must NOT be enriched —
/// only messages matching the server's "Budget not found for provided scope"
/// marker are rewritten.
#[tokio::test]
async fn create_reservation_404_other_not_found_is_not_enriched() {
    let (server, client) = setup().await;

    Mock::given(method("POST"))
        .and(path("/v1/reservations"))
        .respond_with(ResponseTemplate::new(404).set_body_json(json!({
            "error": "NOT_FOUND",
            "message": "Tenant not found: ghost"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let req = ReservationCreateRequest::builder()
        .subject(Subject {
            tenant: Some("ghost".into()),
            ..Default::default()
        })
        .action(Action::new("llm.completion", "gpt-4o"))
        .estimate(Amount::tokens(1000))
        .build();

    let err = client.create_reservation(&req).await.unwrap_err();
    match err {
        Error::Api { message, .. } => {
            assert_eq!(message, "Tenant not found: ghost");
            assert!(!message.contains("unit="));
        }
        other => panic!("expected Api error, got {other:?}"),
    }
}