dirge-agent 0.21.0

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
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
pub(crate) mod command;
// Advisory cross-process lock serializing OAuth refresh writes (dirge-m1o5).
pub(crate) mod file_lock;
// Shared 0600 file-store + expiry + account-id helpers used by both OAuth stores.
pub(crate) mod file_store;
// Kimi Code (Moonshot) device-code OAuth flow + device identity headers.
pub(crate) mod kimi_device;
// Staged for downstream CLI/provider beads; this child owns the tested protocol flow.
pub(crate) mod oauth_pkce;
#[allow(dead_code)]
pub(crate) mod openai_device;
pub(crate) mod openai_oauth;
// Staged for downstream provider/CLI beads; this child owns persistence behavior.
#[allow(dead_code)]
pub(crate) mod store;

#[cfg(test)]
pub(crate) static DIRGE_DATA_DIR_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[cfg(test)]
mod command_tests {
    use super::command::{
        OpenAiCredentialStore, OpenAiLoginFlow, login_openai_with, run_auth_action_with,
    };
    use super::openai_device::{
        DeviceAuthError, DeviceAuthHttp, DeviceAuthRuntime, DeviceCode, HttpResponse, OAuthTokens,
        OpenAiDeviceAuthFlow, Result as DeviceAuthResult,
    };
    use super::store::{OpenAiAuthStore, OpenAiOAuthCredential};
    use crate::cli::AuthAction;
    use serde_json::json;
    use std::collections::VecDeque;
    use std::future::Future;
    use std::path::{Path, PathBuf};
    use std::pin::Pin;
    use std::sync::{Arc, Mutex};
    use std::time::{Duration, Instant};

    struct TestDir(PathBuf);

    impl TestDir {
        fn new(tag: &str) -> Self {
            let path = std::env::temp_dir().join(format!(
                "dirge_auth_command_{tag}_{}_{}",
                std::process::id(),
                uuid::Uuid::new_v4().simple()
            ));
            std::fs::create_dir_all(&path).unwrap();
            Self(path)
        }

        fn path(&self) -> &Path {
            &self.0
        }

        fn auth_path(&self) -> PathBuf {
            self.path().join("auth.json")
        }
    }

    impl Drop for TestDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    #[derive(Clone)]
    struct FakeHttp {
        responses: Arc<Mutex<VecDeque<DeviceAuthResult<HttpResponse>>>>,
    }

    impl FakeHttp {
        fn new(responses: impl IntoIterator<Item = DeviceAuthResult<HttpResponse>>) -> Self {
            Self {
                responses: Arc::new(Mutex::new(responses.into_iter().collect())),
            }
        }
    }

    impl DeviceAuthHttp for FakeHttp {
        fn post_json(
            &self,
            _url: String,
            _body: serde_json::Value,
        ) -> Pin<Box<dyn Future<Output = DeviceAuthResult<HttpResponse>> + Send + '_>> {
            Box::pin(async move { self.responses.lock().unwrap().pop_front().unwrap() })
        }

        fn post_form(
            &self,
            _url: String,
            _form: Vec<(String, String)>,
        ) -> Pin<Box<dyn Future<Output = DeviceAuthResult<HttpResponse>> + Send + '_>> {
            Box::pin(async move { self.responses.lock().unwrap().pop_front().unwrap() })
        }
    }

    #[derive(Clone)]
    struct FakeRuntime {
        now: Instant,
    }

    impl FakeRuntime {
        fn new() -> Self {
            Self {
                now: Instant::now(),
            }
        }
    }

    impl DeviceAuthRuntime for FakeRuntime {
        fn now(&self) -> Instant {
            self.now
        }

        fn sleep(&self, _duration: Duration) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
            Box::pin(async {})
        }
    }

    #[derive(Clone)]
    struct FakeLoginFlow {
        state: Arc<Mutex<FakeLoginFlowState>>,
    }

    struct FakeLoginFlowState {
        device_code: Option<DeviceAuthResult<DeviceCode>>,
        tokens: Option<DeviceAuthResult<OAuthTokens>>,
        completed_with: Option<DeviceCode>,
    }

    impl FakeLoginFlow {
        fn new(device_code: DeviceCode, tokens: OAuthTokens) -> Self {
            Self {
                state: Arc::new(Mutex::new(FakeLoginFlowState {
                    device_code: Some(Ok(device_code)),
                    tokens: Some(Ok(tokens)),
                    completed_with: None,
                })),
            }
        }

        fn completed_with(&self) -> Option<DeviceCode> {
            self.state.lock().unwrap().completed_with.clone()
        }
    }

    impl OpenAiLoginFlow for FakeLoginFlow {
        fn request_device_code(
            &self,
        ) -> Pin<Box<dyn Future<Output = DeviceAuthResult<DeviceCode>> + Send + '_>> {
            Box::pin(async move { self.state.lock().unwrap().device_code.take().unwrap() })
        }

        fn complete_device_code_login(
            &self,
            device_code: DeviceCode,
        ) -> Pin<Box<dyn Future<Output = DeviceAuthResult<OAuthTokens>> + Send + '_>> {
            Box::pin(async move {
                let mut state = self.state.lock().unwrap();
                state.completed_with = Some(device_code);
                state.tokens.take().unwrap()
            })
        }
    }

    #[derive(Clone)]
    struct FakeStore {
        path: PathBuf,
        state: Arc<Mutex<FakeStoreState>>,
    }

    struct FakeStoreState {
        saved: Vec<OpenAiOAuthCredential>,
        save_error: Option<&'static str>,
    }

    impl FakeStore {
        fn new(path: PathBuf) -> Self {
            Self {
                path,
                state: Arc::new(Mutex::new(FakeStoreState {
                    saved: Vec::new(),
                    save_error: None,
                })),
            }
        }

        fn with_save_error(path: PathBuf, save_error: &'static str) -> Self {
            Self {
                path,
                state: Arc::new(Mutex::new(FakeStoreState {
                    saved: Vec::new(),
                    save_error: Some(save_error),
                })),
            }
        }

        fn saved(&self) -> Vec<OpenAiOAuthCredential> {
            self.state.lock().unwrap().saved.clone()
        }
    }

    impl OpenAiCredentialStore for FakeStore {
        fn path(&self) -> &Path {
            &self.path
        }

        fn save_openai(&self, credential: &OpenAiOAuthCredential) -> anyhow::Result<()> {
            let mut state = self.state.lock().unwrap();
            if let Some(save_error) = state.save_error.take() {
                anyhow::bail!(save_error);
            }
            state.saved.push(credential.clone());
            Ok(())
        }
    }

    fn response(status: u16, body: serde_json::Value) -> DeviceAuthResult<HttpResponse> {
        Ok(HttpResponse {
            status,
            body: body.to_string(),
        })
    }

    fn flow(http: FakeHttp) -> OpenAiDeviceAuthFlow<FakeHttp, FakeRuntime> {
        OpenAiDeviceAuthFlow::with_parts(
            "https://auth.openai.com",
            "client-test",
            http,
            FakeRuntime::new(),
        )
    }

    fn device_code() -> DeviceCode {
        DeviceCode {
            verification_url: "https://auth.openai.com/codex/device".to_string(),
            user_code: "USER-CODE".to_string(),
            device_auth_id: "DEVICE-AUTH-ID".to_string(),
            interval: Duration::from_secs(5),
        }
    }

    fn tokens(expires_in: Option<u64>) -> OAuthTokens {
        OAuthTokens {
            access_token: "ACCESS-TOKEN".to_string(),
            refresh_token: "REFRESH-TOKEN".to_string(),
            id_token: "ID-TOKEN".to_string(),
            account_id: None,
            expires_in,
        }
    }

    fn tokens_with_account(account_id: &str) -> OAuthTokens {
        OAuthTokens {
            account_id: Some(account_id.to_string()),
            ..tokens(Some(3600))
        }
    }

    #[tokio::test]
    async fn auth_action_dispatch_invokes_injected_openai_login() {
        let calls = Arc::new(Mutex::new(0));

        run_auth_action_with(&AuthAction::Openai { device_code: false }, || {
            let calls = calls.clone();
            async move {
                *calls.lock().unwrap() += 1;
                Ok(())
            }
        })
        .await
        .unwrap();

        assert_eq!(*calls.lock().unwrap(), 1);
    }

    #[tokio::test]
    async fn openai_login_with_fake_flow_and_store_saves_credential_and_redacts_stdout() {
        let flow = FakeLoginFlow::new(device_code(), tokens(Some(3600)));
        let store = FakeStore::new(PathBuf::from("/tmp/fake-auth.json"));
        let mut stdout = Vec::new();

        login_openai_with(flow.clone(), store.clone(), 1_700_000_000_000, &mut stdout)
            .await
            .unwrap();

        assert_eq!(
            flow.completed_with().unwrap().device_auth_id,
            "DEVICE-AUTH-ID"
        );
        let saved = store.saved();
        assert_eq!(saved.len(), 1);
        let credential = &saved[0];
        assert_eq!(credential.access_token(), "ACCESS-TOKEN");
        assert_eq!(credential.refresh_token(), "REFRESH-TOKEN");
        assert_eq!(credential.id_token(), Some("ID-TOKEN"));
        assert_eq!(credential.expires_at_epoch_ms(), 1_700_003_600_000);

        let stdout = String::from_utf8(stdout).unwrap();
        assert!(stdout.contains("https://auth.openai.com/codex/device"));
        assert!(stdout.contains("USER-CODE"));
        assert!(stdout.contains("/tmp/fake-auth.json"));
        assert!(!stdout.contains("ACCESS-TOKEN"));
        assert!(!stdout.contains("REFRESH-TOKEN"));
        assert!(!stdout.contains("ID-TOKEN"));
        assert!(!stdout.contains("DEVICE-AUTH-ID"));
    }

    #[tokio::test]
    async fn openai_login_saves_optional_account_id_from_token_response() {
        let flow = FakeLoginFlow::new(device_code(), tokens_with_account("acct-login"));
        let store = FakeStore::new(PathBuf::from("/tmp/fake-auth.json"));
        let mut stdout = Vec::new();

        login_openai_with(flow, store.clone(), 1_700_000_000_000, &mut stdout)
            .await
            .unwrap();

        let saved = store.saved();
        assert_eq!(saved.len(), 1);
        assert_eq!(saved[0].account_id(), Some("acct-login"));
        let stdout = String::from_utf8(stdout).unwrap();
        assert!(!stdout.contains("ACCESS-TOKEN"));
        assert!(!stdout.contains("REFRESH-TOKEN"));
        assert!(!stdout.contains("ID-TOKEN"));
    }

    #[tokio::test]
    async fn openai_login_propagates_fake_store_error_without_leaking_tokens_to_stdout() {
        let flow = FakeLoginFlow::new(device_code(), tokens(Some(3600)));
        let store = FakeStore::with_save_error(PathBuf::from("/tmp/fake-auth.json"), "disk full");
        let mut stdout = Vec::new();

        let err = login_openai_with(flow, store.clone(), 1_700_000_000_000, &mut stdout)
            .await
            .unwrap_err();

        assert!(err.to_string().contains("disk full"));
        assert!(store.saved().is_empty());
        let stdout = String::from_utf8(stdout).unwrap();
        assert!(stdout.contains("USER-CODE"));
        assert!(!stdout.contains("OpenAI authorization saved"));
        assert!(!stdout.contains("ACCESS-TOKEN"));
        assert!(!stdout.contains("REFRESH-TOKEN"));
        assert!(!stdout.contains("ID-TOKEN"));
    }

    #[tokio::test]
    async fn openai_login_prints_device_instructions_and_saves_tokens_under_data_dir() {
        let dir = TestDir::new("success");
        let store = OpenAiAuthStore::at(dir.auth_path());
        let http = FakeHttp::new([
            response(
                200,
                json!({
                    "device_auth_id": "DEVICE-AUTH-ID",
                    "user_code": "USER-CODE",
                    "interval": 5
                }),
            ),
            response(
                200,
                json!({
                    "authorization_code": "AUTH-CODE",
                    "code_challenge": "challenge",
                    "code_verifier": "verifier"
                }),
            ),
            response(
                200,
                json!({
                    "access_token": "ACCESS-TOKEN",
                    "refresh_token": "REFRESH-TOKEN",
                    "id_token": "ID-TOKEN",
                    "expires_in": 3600
                }),
            ),
        ]);
        let mut stdout = Vec::new();

        login_openai_with(flow(http), store.clone(), 1_700_000_000_000, &mut stdout)
            .await
            .unwrap();

        assert_eq!(store.path(), dir.auth_path());
        assert!(store.path().starts_with(dir.path()));
        let stdout = String::from_utf8(stdout).unwrap();
        assert!(stdout.contains("https://auth.openai.com/codex/device"));
        assert!(stdout.contains("USER-CODE"));
        assert!(stdout.contains("Do not share"));
        assert!(stdout.contains(store.path().to_string_lossy().as_ref()));
        assert!(!stdout.contains("ACCESS-TOKEN"));
        assert!(!stdout.contains("REFRESH-TOKEN"));
        assert!(!stdout.contains("ID-TOKEN"));
        assert!(!stdout.contains("AUTH-CODE"));
        assert!(!stdout.contains("DEVICE-AUTH-ID"));

        let saved = std::fs::read_to_string(store.path()).unwrap();
        assert!(saved.contains("ACCESS-TOKEN"));
        assert!(saved.contains("REFRESH-TOKEN"));
        assert!(saved.contains("ID-TOKEN"));
        assert!(saved.contains("1700003600000"));
    }

    #[tokio::test]
    async fn openai_login_disabled_error_is_actionable_and_does_not_create_auth_file() {
        let dir = TestDir::new("disabled");
        let store = OpenAiAuthStore::at(dir.auth_path());
        let http = FakeHttp::new([response(404, json!({"error": "not found"}))]);
        let mut stdout = Vec::new();

        let err = login_openai_with(flow(http), store.clone(), 1_700_000_000_000, &mut stdout)
            .await
            .unwrap_err();
        let message = err.to_string();

        assert!(matches!(
            err.downcast_ref::<DeviceAuthError>(),
            Some(DeviceAuthError::DeviceAuthDisabled)
        ));
        assert!(message.contains("enable device-code auth"));
        assert!(message.contains("ChatGPT Codex security settings"));
        assert!(!message.contains("ACCESS-TOKEN"));
        assert!(!message.contains("REFRESH-TOKEN"));
        assert!(!message.contains("ID-TOKEN"));
        assert!(!store.path().exists());
        assert!(stdout.is_empty());
    }

    #[tokio::test]
    async fn openai_login_without_expires_in_uses_conservative_access_expiry() {
        let dir = TestDir::new("missing_expires");
        let store = OpenAiAuthStore::at(dir.auth_path());
        let http = FakeHttp::new([
            response(
                200,
                json!({
                    "device_auth_id": "DEVICE-AUTH-ID",
                    "user_code": "USER-CODE",
                    "interval": 5
                }),
            ),
            response(
                200,
                json!({
                    "authorization_code": "AUTH-CODE",
                    "code_challenge": "challenge",
                    "code_verifier": "verifier"
                }),
            ),
            response(
                200,
                json!({
                    "access_token": "ACCESS-TOKEN",
                    "refresh_token": "REFRESH-TOKEN",
                    "id_token": "ID-TOKEN"
                }),
            ),
        ]);
        let mut stdout = Vec::new();

        login_openai_with(flow(http), store.clone(), 1_700_000_000_000, &mut stdout)
            .await
            .unwrap();

        let saved = std::fs::read_to_string(store.path()).unwrap();
        assert!(saved.contains("1700000300000"));
    }

    #[test]
    fn oauth_validation_scripts_isolate_config_dir() {
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        for script in [
            "scripts/validate-openai-oauth.sh",
            "scripts/openai-oauth-interactive.sh",
        ] {
            let body = std::fs::read_to_string(root.join(script)).unwrap();

            assert!(
                body.contains("DIRGE_OAUTH_VALIDATION_CONFIG_DIR"),
                "{script} must document its isolated config dir override"
            );
            assert!(
                body.contains("export DIRGE_CONFIG_DIR=\"$config_dir\""),
                "{script} must export an isolated DIRGE_CONFIG_DIR"
            );
            assert!(
                body.contains("rm -rf -- \"$config_dir\""),
                "{script} must clear stale validation config before each run"
            );
            assert!(
                body.contains("Using DIRGE_CONFIG_DIR"),
                "{script} must print the non-secret config dir in validation evidence"
            );
        }
    }
}

#[cfg(test)]
mod kimi_command_tests {
    use super::command::{KimiCredentialStore, KimiLoginFlow, login_kimi_with};
    use super::kimi_device::{
        DeviceAuthorization, KimiAuthError, Result as KimiAuthResult, TokenInfo,
    };
    use super::store::{KimiAuthStore, KimiOAuthCredential};
    use std::future::Future;
    use std::path::{Path, PathBuf};
    use std::pin::Pin;
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    struct TestDir(PathBuf);

    impl TestDir {
        fn new(tag: &str) -> Self {
            let path = std::env::temp_dir().join(format!(
                "dirge_kimi_command_{tag}_{}_{}",
                std::process::id(),
                uuid::Uuid::new_v4().simple()
            ));
            std::fs::create_dir_all(&path).unwrap();
            Self(path)
        }

        fn auth_path(&self) -> PathBuf {
            self.0.join("auth.json")
        }
    }

    impl Drop for TestDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    #[derive(Clone)]
    struct FakeLoginFlow {
        state: Arc<Mutex<FakeLoginFlowState>>,
    }

    struct FakeLoginFlowState {
        authorization: Option<KimiAuthResult<DeviceAuthorization>>,
        tokens: Option<KimiAuthResult<TokenInfo>>,
        completed_with: Option<DeviceAuthorization>,
    }

    impl FakeLoginFlow {
        fn new(authorization: DeviceAuthorization, tokens: TokenInfo) -> Self {
            Self {
                state: Arc::new(Mutex::new(FakeLoginFlowState {
                    authorization: Some(Ok(authorization)),
                    tokens: Some(Ok(tokens)),
                    completed_with: None,
                })),
            }
        }

        fn completed_with(&self) -> Option<DeviceAuthorization> {
            self.state.lock().unwrap().completed_with.clone()
        }
    }

    impl KimiLoginFlow for FakeLoginFlow {
        fn request_device_authorization(
            &self,
        ) -> Pin<Box<dyn Future<Output = KimiAuthResult<DeviceAuthorization>> + Send + '_>>
        {
            Box::pin(async move { self.state.lock().unwrap().authorization.take().unwrap() })
        }

        fn complete_device_login(
            &self,
            authorization: DeviceAuthorization,
        ) -> Pin<Box<dyn Future<Output = KimiAuthResult<TokenInfo>> + Send + '_>> {
            Box::pin(async move {
                let mut state = self.state.lock().unwrap();
                state.completed_with = Some(authorization);
                state.tokens.take().unwrap()
            })
        }
    }

    #[derive(Clone)]
    struct FakeStore {
        path: PathBuf,
        state: Arc<Mutex<FakeStoreState>>,
    }

    struct FakeStoreState {
        saved: Vec<KimiOAuthCredential>,
        save_error: Option<&'static str>,
    }

    impl FakeStore {
        fn new(path: PathBuf) -> Self {
            Self {
                path,
                state: Arc::new(Mutex::new(FakeStoreState {
                    saved: Vec::new(),
                    save_error: None,
                })),
            }
        }

        fn with_save_error(path: PathBuf, save_error: &'static str) -> Self {
            Self {
                path,
                state: Arc::new(Mutex::new(FakeStoreState {
                    saved: Vec::new(),
                    save_error: Some(save_error),
                })),
            }
        }

        fn saved(&self) -> Vec<KimiOAuthCredential> {
            self.state.lock().unwrap().saved.clone()
        }
    }

    impl KimiCredentialStore for FakeStore {
        fn path(&self) -> &Path {
            &self.path
        }

        fn save_kimi(&self, credential: &KimiOAuthCredential) -> anyhow::Result<()> {
            let mut state = self.state.lock().unwrap();
            if let Some(save_error) = state.save_error.take() {
                anyhow::bail!(save_error);
            }
            state.saved.push(credential.clone());
            Ok(())
        }
    }

    fn authorization() -> DeviceAuthorization {
        DeviceAuthorization {
            user_code: "USER-CODE".to_string(),
            device_code: "DEVICE-CODE".to_string(),
            verification_uri: "https://kimi.com/device".to_string(),
            verification_uri_complete: "https://kimi.com/device?code=USER-CODE".to_string(),
            interval: Duration::from_secs(5),
        }
    }

    fn tokens() -> TokenInfo {
        TokenInfo {
            access_token: "ACCESS-TOKEN".to_string(),
            refresh_token: "REFRESH-TOKEN".to_string(),
            expires_at_epoch_ms: 1_700_000_900_000,
            scope: String::new(),
            token_type: "Bearer".to_string(),
        }
    }

    #[tokio::test]
    async fn kimi_login_with_fake_flow_and_store_saves_credential_and_redacts_stdout() {
        let flow = FakeLoginFlow::new(authorization(), tokens());
        let store = FakeStore::new(PathBuf::from("/tmp/fake-kimi-auth.json"));
        let mut stdout = Vec::new();

        login_kimi_with(flow.clone(), store.clone(), &mut stdout)
            .await
            .unwrap();

        assert_eq!(flow.completed_with().unwrap().device_code, "DEVICE-CODE");
        let saved = store.saved();
        assert_eq!(saved.len(), 1);
        let credential = &saved[0];
        assert_eq!(credential.access_token(), "ACCESS-TOKEN");
        assert_eq!(credential.refresh_token(), "REFRESH-TOKEN");
        assert_eq!(credential.expires_at_epoch_ms(), 1_700_000_900_000);

        let stdout = String::from_utf8(stdout).unwrap();
        assert!(stdout.contains("https://kimi.com/device?code=USER-CODE"));
        assert!(stdout.contains("USER-CODE"));
        assert!(stdout.contains("/tmp/fake-kimi-auth.json"));
        assert!(!stdout.contains("ACCESS-TOKEN"));
        assert!(!stdout.contains("REFRESH-TOKEN"));
        assert!(!stdout.contains("DEVICE-CODE"));
    }

    #[tokio::test]
    async fn kimi_login_propagates_store_error_without_leaking_tokens_to_stdout() {
        let flow = FakeLoginFlow::new(authorization(), tokens());
        let store =
            FakeStore::with_save_error(PathBuf::from("/tmp/fake-kimi-auth.json"), "disk full");
        let mut stdout = Vec::new();

        let err = login_kimi_with(flow, store.clone(), &mut stdout)
            .await
            .unwrap_err();

        assert!(err.to_string().contains("disk full"));
        assert!(store.saved().is_empty());
        let stdout = String::from_utf8(stdout).unwrap();
        assert!(stdout.contains("USER-CODE"));
        assert!(!stdout.contains("Kimi authorization saved"));
        assert!(!stdout.contains("ACCESS-TOKEN"));
        assert!(!stdout.contains("REFRESH-TOKEN"));
    }

    #[tokio::test]
    async fn kimi_login_flow_error_does_not_create_auth_file() {
        let dir = TestDir::new("flow_error");
        let store = FakeStore::new(dir.auth_path());
        let flow = FakeLoginFlow {
            state: Arc::new(Mutex::new(FakeLoginFlowState {
                authorization: Some(Err(KimiAuthError::DeviceAuthorizationStatus {
                    status: 500,
                })),
                tokens: None,
                completed_with: None,
            })),
        };
        let mut stdout = Vec::new();

        let err = login_kimi_with(flow, store.clone(), &mut stdout)
            .await
            .unwrap_err();

        assert!(
            err.downcast_ref::<KimiAuthError>()
                .is_some_and(|err| matches!(
                    err,
                    KimiAuthError::DeviceAuthorizationStatus { status: 500 }
                ))
        );
        assert!(!err.to_string().contains("ACCESS-TOKEN"));
        assert!(stdout.is_empty());
    }

    #[tokio::test]
    async fn kimi_login_with_real_store_writes_tokens_under_data_dir() {
        let dir = TestDir::new("success");
        let flow = FakeLoginFlow::new(authorization(), tokens());
        let store = KimiAuthStore::at(dir.auth_path());
        let mut stdout = Vec::new();

        login_kimi_with(flow, store.clone(), &mut stdout)
            .await
            .unwrap();

        let stdout = String::from_utf8(stdout).unwrap();
        assert!(stdout.contains(store.path().to_string_lossy().as_ref()));
        assert!(!stdout.contains("ACCESS-TOKEN"));
        assert!(!stdout.contains("REFRESH-TOKEN"));

        let saved = std::fs::read_to_string(store.path()).unwrap();
        assert!(saved.contains("\"kimi\""));
        assert!(saved.contains("ACCESS-TOKEN"));
        assert!(saved.contains("REFRESH-TOKEN"));
        assert!(saved.contains("1700000900000"));
    }

    #[test]
    fn kimi_oauth_validation_script_isolates_config_dir() {
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        let body = std::fs::read_to_string(root.join("scripts/validate-kimi-oauth.sh")).unwrap();

        assert!(
            body.contains("DIRGE_OAUTH_VALIDATION_CONFIG_DIR"),
            "script must document its isolated config dir override"
        );
        assert!(
            body.contains("export DIRGE_CONFIG_DIR=\"$config_dir\""),
            "script must export an isolated DIRGE_CONFIG_DIR"
        );
        assert!(
            body.contains("rm -rf -- \"$config_dir\""),
            "script must clear stale validation config before each run"
        );
        assert!(
            body.contains("Using DIRGE_CONFIG_DIR"),
            "script must print the non-secret config dir in validation evidence"
        );
    }
}