tsk-ai 0.10.6

tsk-tsk: keeping your agents out of trouble with sandboxed coding agent automation
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
use super::Agent;
use crate::context::tsk_env::TskEnv;
use async_trait::async_trait;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Arc, OnceLock};
use std::time::Duration;

pub mod claude_log_processor;
pub use claude_log_processor::ClaudeLogProcessor;

/// Minimum remaining token lifetime before we consider it expired (5 minutes).
const TOKEN_EXPIRY_BUFFER: Duration = Duration::from_millis(300_000);

const NOT_LOGGED_IN_ERROR: &str = "Claude CLI is not logged in. Please run 'claude login' first.";

/// Result of checking the Claude OAuth token's validity.
#[derive(Debug)]
pub enum OAuthTokenStatus {
    /// Token is valid and won't expire within the buffer window.
    Valid,
    /// Token is expired or will expire within the buffer window.
    ExpiredOrExpiring,
}

/// Checks Claude's OAuth token expiration from the credentials file.
///
/// Reads `~/.claude/.credentials.json` and inspects `claudeAiOauth.expiresAt`
/// (a Unix timestamp in milliseconds). Returns the token status indicating
/// whether the token is valid or expired/expiring.
///
/// # Errors
///
/// Returns an error string if the credentials file is missing, unreadable,
/// or does not contain the expected JSON structure.
pub fn check_oauth_token_validity() -> Result<OAuthTokenStatus, String> {
    let home =
        std::env::var("HOME").map_err(|_| "HOME environment variable not set".to_string())?;
    let credentials_path = PathBuf::from(home)
        .join(".claude")
        .join(".credentials.json");

    check_oauth_token_validity_at(&credentials_path)
}

/// Checks OAuth token validity from a specific credentials file path.
///
/// This is the implementation behind [`check_oauth_token_validity`], separated
/// to allow testing with arbitrary file paths.
fn check_oauth_token_validity_at(credentials_path: &Path) -> Result<OAuthTokenStatus, String> {
    let contents = std::fs::read_to_string(credentials_path).map_err(|e| {
        format!(
            "Failed to read credentials file at {}: {}",
            credentials_path.display(),
            e
        )
    })?;

    let json: serde_json::Value =
        serde_json::from_str(&contents).map_err(|e| format!("Failed to parse credentials: {e}"))?;

    let expires_at_ms = json
        .get("claudeAiOauth")
        .and_then(|oauth| oauth.get("expiresAt"))
        .and_then(|v| v.as_i64())
        .ok_or_else(|| "Credentials file missing claudeAiOauth.expiresAt field".to_string())?;

    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|e| format!("System time error: {e}"))?
        .as_millis() as i64;

    let remaining_ms = expires_at_ms - now_ms;

    if remaining_ms <= TOKEN_EXPIRY_BUFFER.as_millis() as i64 {
        Ok(OAuthTokenStatus::ExpiredOrExpiring)
    } else {
        Ok(OAuthTokenStatus::Valid)
    }
}

/// Claude AI agent implementation
pub struct ClaudeAgent {
    tsk_env: Option<Arc<TskEnv>>,
    version_cache: OnceLock<String>,
}

impl ClaudeAgent {
    /// Creates a new ClaudeAgent with the provided TSK environment
    ///
    /// # Arguments
    /// * `tsk_env` - Arc reference to the TskEnv instance containing environment settings
    pub fn with_tsk_env(tsk_env: Arc<TskEnv>) -> Self {
        Self {
            tsk_env: Some(tsk_env),
            version_cache: OnceLock::new(),
        }
    }

    fn get_claude_config_dir(&self) -> PathBuf {
        self.tsk_env
            .as_ref()
            .expect("TskEnv should always be present")
            .claude_config_dir()
            .to_path_buf()
    }

    /// Checks login status via `claude auth status --json`.
    /// Returns `Some(true)` if logged in, `Some(false)` if not logged in,
    /// or `None` if the command is unavailable (older CLI versions).
    fn check_auth_status() -> Option<bool> {
        let output = Command::new("claude")
            .args(["auth", "status", "--json"])
            .stderr(std::process::Stdio::null())
            .output()
            .ok()?;

        if !output.status.success() {
            return None;
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let status: serde_json::Value = serde_json::from_str(stdout.trim()).ok()?;
        Some(status.get("loggedIn") == Some(&serde_json::Value::Bool(true)))
    }
}

impl Default for ClaudeAgent {
    fn default() -> Self {
        Self::with_tsk_env(Arc::new(TskEnv::new().expect("Failed to create TskEnv")))
    }
}

/// Creates a tar archive containing a single file
///
/// # Arguments
/// * `filename` - The name of the file to store in the archive
/// * `contents` - The file contents as bytes
///
/// # Returns
/// The tar archive data as a byte vector
fn create_tar_with_file(filename: &str, contents: &[u8]) -> Vec<u8> {
    let mut builder = tar::Builder::new(Vec::new());

    let mut header = tar::Header::new_gnu();
    header.set_path(filename).expect("Invalid filename");
    header.set_size(contents.len() as u64);
    header.set_mode(0o644);
    // Use host UID/GID so files are owned by the container's runtime user
    // SAFETY: getuid/getgid are simple syscalls with no preconditions
    header.set_uid(unsafe { libc::getuid() } as u64);
    header.set_gid(unsafe { libc::getgid() } as u64);
    header.set_mtime(0);
    header.set_cksum();

    builder
        .append(&header, contents)
        .expect("Failed to append file to tar");

    builder.into_inner().expect("Failed to finish tar archive")
}

#[async_trait]
impl Agent for ClaudeAgent {
    fn build_command(&self, instruction_path: &str, is_interactive: bool) -> Vec<String> {
        // Get just the filename from the instruction path
        let filename = Path::new(instruction_path)
            .file_name()
            .and_then(|f| f.to_str())
            .unwrap_or("instructions.md");

        if is_interactive {
            let normal_command = format!(
                "cat /instructions/{} | claude -p --verbose --output-format stream-json --dangerously-skip-permissions",
                filename
            );

            vec![
                "sh".to_string(),
                "-c".to_string(),
                format!(
                    r#"sleep 0.5; echo '=== Task Instructions ==='; cat /instructions/{}; echo; echo '=== Normal Command ==='; echo '{}'; echo; echo '=== Starting Interactive Claude Code Session ==='; echo 'You can now interact with Claude Code directly.'; echo 'Type "exit" or Ctrl+D to end the session.'; echo; exec /bin/bash"#,
                    filename, normal_command
                ),
            ]
        } else {
            vec![
                "sh".to_string(),
                "-c".to_string(),
                format!(
                    // Pipe instructions to claude, capture all output (stdout + stderr), and tee to log file
                    // This allows TSK to process output in real-time while preserving a complete log
                    "cat /instructions/{} | claude -p --verbose --output-format stream-json --dangerously-skip-permissions 2>&1 | tee /output/claude-log.txt",
                    filename
                ),
            ]
        }
    }

    fn volumes(&self) -> Vec<(String, String, String)> {
        let claude_config_dir = self.get_claude_config_dir();

        vec![
            // Claude config directory
            (
                claude_config_dir.to_string_lossy().to_string(),
                "/home/agent/.claude".to_string(),
                "".to_string(),
            ),
        ]
    }

    fn environment(&self) -> Vec<(String, String)> {
        vec![]
    }

    fn create_log_processor(
        &self,
        _task: Option<&crate::task::Task>,
    ) -> Box<dyn super::LogProcessor> {
        Box::new(ClaudeLogProcessor::new())
    }

    fn name(&self) -> &str {
        "claude"
    }

    async fn validate(&self) -> Result<(), String> {
        // Skip validation in test environments
        if cfg!(test) {
            return Ok(());
        }

        // Try `claude auth status` first (available in newer CLI versions)
        if let Some(logged_in) = Self::check_auth_status() {
            return if logged_in {
                Ok(())
            } else {
                Err(NOT_LOGGED_IN_ERROR.to_string())
            };
        }

        // Fall back to directory check for older CLI versions
        let claude_config_dir = self.get_claude_config_dir();
        if !claude_config_dir.exists() {
            return Err(format!(
                "Claude configuration directory not found at {}. Please run 'claude login' first.",
                claude_config_dir.display()
            ));
        }

        Ok(())
    }

    async fn warmup(&self) -> Result<(), String> {
        // Skip warmup in test environments
        if cfg!(test) {
            return Ok(());
        }

        // Step 1: Check auth status (prefer `auth status`, fall back to prompt)
        match Self::check_auth_status() {
            Some(true) => {}
            Some(false) => {
                return Err(NOT_LOGGED_IN_ERROR.to_string());
            }
            None => {
                // Fall back to prompting Claude for older CLI versions
                let output = Command::new("claude")
                    .args([
                        "-p",
                        "--no-session-persistence",
                        "--tools",
                        "",
                        "--model",
                        "sonnet",
                        "say hi and nothing else",
                    ])
                    .output()
                    .map_err(|e| format!("Failed to run Claude CLI: {e}"))?;

                if !output.status.success() {
                    return Err(format!(
                        "Claude CLI failed: {}",
                        String::from_utf8_lossy(&output.stderr)
                    ));
                }
            }
        }

        // Step 2: Export OAuth token on macOS only
        if std::env::consts::OS == "macos" {
            let user = std::env::var("USER").map_err(|_| "USER environment variable not set")?;

            let output = Command::new("sh")
                .arg("-c")
                .arg(format!(
                    "security find-generic-password -a {user} -w -s 'Claude Code-credentials' > ~/.claude/.credentials.json"
                ))
                .output()
                .map_err(|e| format!("Failed to export OAuth token: {e}"))?;

            if !output.status.success() {
                // This might fail if the keychain item doesn't exist yet
                eprintln!("Warning: Could not export OAuth token from keychain");
            }
        }
        Ok(())
    }

    fn version(&self) -> String {
        self.version_cache
            .get_or_init(|| {
                // Skip version detection in test environments
                if cfg!(test) {
                    return "test-claude-1.0.0".to_string();
                }

                // Try to get Claude version from CLI
                match Command::new("claude").arg("--version").output() {
                    Ok(output) if output.status.success() => {
                        let version_str = String::from_utf8_lossy(&output.stdout);
                        // Parse version string, typically in format "claude 0.3.0" or similar
                        // Clean up the version string to remove extra whitespace and newlines
                        let cleaned = version_str.trim().to_string();
                        if cleaned.is_empty() {
                            "unknown".to_string()
                        } else {
                            // Replace spaces with hyphens for Docker compatibility
                            cleaned.replace(' ', "-").replace('\n', "")
                        }
                    }
                    Ok(_) => {
                        eprintln!("Warning: Failed to get Claude version (command failed)");
                        "unknown".to_string()
                    }
                    Err(e) => {
                        eprintln!("Warning: Failed to run claude --version: {}", e);
                        "unknown".to_string()
                    }
                }
            })
            .clone()
    }

    fn files_to_copy(&self) -> Vec<(Vec<u8>, String)> {
        // Get the home directory (parent of .claude config dir)
        let claude_config_dir = self.get_claude_config_dir();
        let home_dir = match claude_config_dir.parent() {
            Some(dir) => dir,
            None => return vec![],
        };

        let claude_json_path = home_dir.join(".claude.json");

        // Read the file if it exists
        if claude_json_path.exists() {
            match std::fs::read(&claude_json_path) {
                Ok(contents) => {
                    let tar_data = create_tar_with_file(".claude.json", &contents);
                    vec![(tar_data, "/home/agent".to_string())]
                }
                Err(e) => {
                    eprintln!(
                        "Warning: Failed to read {}: {}",
                        claude_json_path.display(),
                        e
                    );
                    vec![]
                }
            }
        } else {
            vec![]
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context::AppContext;

    #[test]
    fn test_claude_agent_properties() {
        let app_context = AppContext::builder().build();
        let tsk_env = app_context.tsk_env();
        let agent = ClaudeAgent::with_tsk_env(tsk_env);

        // Test name
        assert_eq!(agent.name(), "claude");

        // Test volumes
        let volumes = agent.volumes();
        assert_eq!(volumes.len(), 1);

        // Should mount .claude directory
        let volume_paths: Vec<&str> = volumes
            .iter()
            .map(|(_, container_path, _)| container_path.as_str())
            .collect();
        assert!(volume_paths.contains(&"/home/agent/.claude"));

        // Environment variables are set by DockerManager, not the agent
        let env = agent.environment();
        assert!(env.is_empty());
    }

    #[test]
    fn test_claude_agent_build_command() {
        let app_context = AppContext::builder().build();
        let tsk_env = app_context.tsk_env();
        let agent = ClaudeAgent::with_tsk_env(tsk_env);

        // Test non-interactive mode with full path
        let command = agent.build_command("/tmp/instructions.md", false);
        assert_eq!(command.len(), 3);
        assert_eq!(command[0], "sh");
        assert_eq!(command[1], "-c");
        assert!(command[2].contains("cat /instructions/instructions.md"));
        assert!(command[2].contains("claude -p --verbose --output-format stream-json"));
        assert!(command[2].contains("tee /output/claude-log.txt"));

        // Test non-interactive mode with complex path
        let command = agent.build_command("/path/to/task/instructions.txt", false);
        assert!(command[2].contains("cat /instructions/instructions.txt"));
        assert!(command[2].contains("tee /output/claude-log.txt"));

        // Test interactive mode
        let command = agent.build_command("/tmp/instructions.md", true);
        assert_eq!(command.len(), 3);
        assert_eq!(command[0], "sh");
        assert_eq!(command[1], "-c");

        // Check that it has a sleep to allow attach to be ready
        assert!(command[2].starts_with("sleep 0.5;"));

        // Check that it shows the instructions
        assert!(command[2].contains("=== Task Instructions ==="));
        assert!(command[2].contains("cat /instructions/instructions.md"));

        // Check that it shows the normal command
        assert!(command[2].contains("=== Normal Command ==="));
        assert!(command[2].contains("claude -p --verbose --output-format stream-json"));

        // Check that it starts an interactive session
        assert!(command[2].contains("=== Starting Interactive Claude Code Session ==="));
        assert!(command[2].contains("exec /bin/bash"));
    }

    #[tokio::test]
    async fn test_claude_agent_validate_without_config() {
        // In test mode, validation is skipped so this test just verifies
        // that validate() returns Ok in test environments
        let app_context = AppContext::builder().build();
        let tsk_env = app_context.tsk_env();
        let agent = ClaudeAgent::with_tsk_env(tsk_env);
        let result = agent.validate().await;

        // In test mode, validation is skipped
        assert!(result.is_ok());
    }

    #[test]
    fn test_claude_agent_create_log_processor() {
        let app_context = AppContext::builder().build();
        let tsk_env = app_context.tsk_env();
        let agent = ClaudeAgent::with_tsk_env(tsk_env);

        // Just verify we can create a log processor
        // The actual log processor functionality is tested elsewhere
        let _log_processor = agent.create_log_processor(None);

        // Also test with custom config using AppContext
        use crate::context::AppContext;
        let ctx = AppContext::builder().build();
        let agent_with_config = ClaudeAgent::with_tsk_env(ctx.tsk_env());
        let _ = agent_with_config.create_log_processor(None);
    }

    #[test]
    fn test_claude_agent_version() {
        let app_context = AppContext::builder().build();
        let tsk_env = app_context.tsk_env();
        let agent = ClaudeAgent::with_tsk_env(tsk_env);

        // In test mode, should return test version
        let version = agent.version();
        assert_eq!(version, "test-claude-1.0.0");

        // Test that calling version multiple times returns the same cached value
        let version2 = agent.version();
        assert_eq!(version, version2);
    }

    #[test]
    fn test_create_tar_with_file() {
        use std::io::Read;
        use tar::Archive;

        let contents = b"test file contents";
        let tar_data = super::create_tar_with_file("test.txt", contents);

        // Verify it's a valid tar archive
        let mut archive = Archive::new(tar_data.as_slice());
        let entries: Vec<_> = archive.entries().unwrap().collect();
        assert_eq!(entries.len(), 1);

        // Re-create archive to read the entry
        let mut archive = Archive::new(tar_data.as_slice());
        let mut entry = archive.entries().unwrap().next().unwrap().unwrap();

        // Verify filename
        assert_eq!(entry.path().unwrap().to_str().unwrap(), "test.txt");

        // Verify contents
        let mut extracted_contents = Vec::new();
        entry.read_to_end(&mut extracted_contents).unwrap();
        assert_eq!(extracted_contents, contents);
    }

    #[test]
    fn test_create_tar_with_file_empty_contents() {
        use tar::Archive;

        let tar_data = super::create_tar_with_file("empty.txt", b"");

        let mut archive = Archive::new(tar_data.as_slice());
        let entry = archive.entries().unwrap().next().unwrap().unwrap();
        assert_eq!(entry.size(), 0);
    }

    #[test]
    fn test_files_to_copy_with_existing_file() {
        use std::fs;

        let app_context = AppContext::builder().build();
        let tsk_env = app_context.tsk_env();
        let agent = ClaudeAgent::with_tsk_env(tsk_env.clone());

        // Get the home directory where we'll create the test file
        let home_dir = tsk_env.claude_config_dir().parent().unwrap();
        let claude_json_path = home_dir.join(".claude.json");

        // Create test file
        let test_content = r#"{"test": "data"}"#;
        fs::write(&claude_json_path, test_content).unwrap();

        // Test files_to_copy
        let files = agent.files_to_copy();
        assert_eq!(files.len(), 1);

        let (tar_data, dest_path) = &files[0];
        assert_eq!(dest_path, "/home/agent");

        // Verify tar contains the correct file
        use std::io::Read;
        use tar::Archive;

        let mut archive = Archive::new(tar_data.as_slice());
        let mut entry = archive.entries().unwrap().next().unwrap().unwrap();

        assert_eq!(entry.path().unwrap().to_str().unwrap(), ".claude.json");

        let mut extracted_contents = String::new();
        entry.read_to_string(&mut extracted_contents).unwrap();
        assert_eq!(extracted_contents, test_content);
    }

    #[test]
    fn test_files_to_copy_without_file() {
        let app_context = AppContext::builder().build();
        let tsk_env = app_context.tsk_env();
        let agent = ClaudeAgent::with_tsk_env(tsk_env.clone());

        // Ensure the file doesn't exist
        let home_dir = tsk_env.claude_config_dir().parent().unwrap();
        let claude_json_path = home_dir.join(".claude.json");
        if claude_json_path.exists() {
            std::fs::remove_file(&claude_json_path).unwrap();
        }

        // Test files_to_copy returns empty when file doesn't exist
        let files = agent.files_to_copy();
        assert!(files.is_empty());
    }

    #[test]
    fn test_oauth_token_valid() {
        let dir = tempfile::tempdir().unwrap();
        let creds_path = dir.path().join(".credentials.json");

        // Token expires 1 hour from now
        let expires_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis() as i64
            + 3_600_000;

        let json = format!(
            r#"{{"claudeAiOauth":{{"accessToken":"tok","refreshToken":"ref","expiresAt":{}}}}}"#,
            expires_at
        );
        std::fs::write(&creds_path, json).unwrap();

        let result = check_oauth_token_validity_at(&creds_path).unwrap();
        assert!(
            matches!(result, OAuthTokenStatus::Valid),
            "Expected Valid, got {:?}",
            result
        );
    }

    #[test]
    fn test_oauth_token_expiring_within_buffer() {
        let dir = tempfile::tempdir().unwrap();
        let creds_path = dir.path().join(".credentials.json");

        // Token expires 2 minutes from now (within the 5-minute buffer)
        let expires_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis() as i64
            + 120_000;

        let json = format!(
            r#"{{"claudeAiOauth":{{"accessToken":"tok","refreshToken":"ref","expiresAt":{}}}}}"#,
            expires_at
        );
        std::fs::write(&creds_path, json).unwrap();

        let result = check_oauth_token_validity_at(&creds_path).unwrap();
        assert!(
            matches!(result, OAuthTokenStatus::ExpiredOrExpiring),
            "Expected ExpiredOrExpiring, got {:?}",
            result
        );
    }

    #[test]
    fn test_oauth_token_already_expired() {
        let dir = tempfile::tempdir().unwrap();
        let creds_path = dir.path().join(".credentials.json");

        // Token expired 1 hour ago
        let expires_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis() as i64
            - 3_600_000;

        let json = format!(
            r#"{{"claudeAiOauth":{{"accessToken":"tok","refreshToken":"ref","expiresAt":{}}}}}"#,
            expires_at
        );
        std::fs::write(&creds_path, json).unwrap();

        let result = check_oauth_token_validity_at(&creds_path).unwrap();
        assert!(
            matches!(result, OAuthTokenStatus::ExpiredOrExpiring),
            "Expected ExpiredOrExpiring, got {:?}",
            result
        );
    }

    #[test]
    fn test_oauth_token_missing_file() {
        let dir = tempfile::tempdir().unwrap();
        let creds_path = dir.path().join("nonexistent.json");

        let result = check_oauth_token_validity_at(&creds_path);
        assert!(result.is_err(), "Expected error for missing file");
    }

    #[test]
    fn test_oauth_token_malformed_json() {
        let dir = tempfile::tempdir().unwrap();
        let creds_path = dir.path().join(".credentials.json");
        std::fs::write(&creds_path, "not valid json").unwrap();

        let result = check_oauth_token_validity_at(&creds_path);
        assert!(result.is_err(), "Expected error for malformed JSON");
    }

    #[test]
    fn test_oauth_token_missing_field() {
        let dir = tempfile::tempdir().unwrap();
        let creds_path = dir.path().join(".credentials.json");
        std::fs::write(&creds_path, r#"{"claudeAiOauth":{"accessToken":"tok"}}"#).unwrap();

        let result = check_oauth_token_validity_at(&creds_path);
        assert!(
            result.is_err(),
            "Expected error for missing expiresAt field"
        );
    }
}