selfware 0.2.2

Your personal AI workshop — software you own, software that lasts
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
//! System tests for interactive mode
//!
//! Tests all command paths and edge cases in the interactive CLI mode.
//! These tests use subprocess execution to simulate real user interaction.

use std::io::{Read, Write};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

/// Get the selfware binary path using Cargo-provided path (ensures freshly built binary)
fn get_binary_path() -> String {
    // Allow override via environment variable
    if let Ok(path) = std::env::var("SELFWARE_BINARY") {
        return path;
    }

    // Use Cargo-provided binary path when running via `cargo test`
    // This ensures we always use the binary that was just built
    env!("CARGO_BIN_EXE_selfware").to_string()
}

/// Helper to run selfware with input and capture output with timeout enforcement.
///
/// On timeout, kills the process but still drains stdout/stderr so that
/// partially-flushed output is available to the calling test.
fn run_interactive(input: &str, timeout_secs: u64) -> (String, String, i32) {
    let binary = get_binary_path();
    let mut child = Command::new(&binary)
        .arg("chat")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn selfware");

    // Write input to stdin
    if let Some(mut stdin) = child.stdin.take() {
        stdin.write_all(input.as_bytes()).ok();
        stdin.write_all(b"\n").ok();
    }

    let timeout = Duration::from_secs(timeout_secs);
    let start = Instant::now();
    let poll_interval = Duration::from_millis(100);

    // Poll for completion with timeout
    loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                // Child exited, read output
                let mut stdout_buf = Vec::new();
                let mut stderr_buf = Vec::new();
                if let Some(mut stdout) = child.stdout.take() {
                    stdout.read_to_end(&mut stdout_buf).ok();
                }
                if let Some(mut stderr) = child.stderr.take() {
                    stderr.read_to_end(&mut stderr_buf).ok();
                }
                let stdout = String::from_utf8_lossy(&stdout_buf).to_string();
                let stderr = String::from_utf8_lossy(&stderr_buf).to_string();
                let code = status.code().unwrap_or(-1);
                return (stdout, stderr, code);
            }
            Ok(None) => {
                // Still running, check timeout
                if start.elapsed() >= timeout {
                    child.kill().ok();
                    // Drain stdout/stderr even after kill so partial output is available
                    let output = child.wait_with_output().expect("Failed to wait after kill");
                    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
                    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
                    return (stdout, format!("timeout: {}", stderr), -1);
                }
                std::thread::sleep(poll_interval);
            }
            Err(_) => {
                return ("".to_string(), "process error".to_string(), -1);
            }
        }
    }
}

/// Helper to run selfware 'run' command (non-interactive) with timeout enforcement
/// Uses --yolo to auto-approve tools since non-interactive mode requires it
fn run_task(task: &str, timeout_secs: u64) -> (String, String, i32) {
    let mut child = Command::new(get_binary_path())
        .args(["--yolo", "run", task])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn selfware");

    let timeout = Duration::from_secs(timeout_secs);
    let start = Instant::now();
    let poll_interval = Duration::from_millis(100);

    loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                let mut stdout_buf = Vec::new();
                let mut stderr_buf = Vec::new();
                if let Some(mut stdout) = child.stdout.take() {
                    stdout.read_to_end(&mut stdout_buf).ok();
                }
                if let Some(mut stderr) = child.stderr.take() {
                    stderr.read_to_end(&mut stderr_buf).ok();
                }
                let stdout = String::from_utf8_lossy(&stdout_buf).to_string();
                let stderr = String::from_utf8_lossy(&stderr_buf).to_string();
                let code = status.code().unwrap_or(-1);
                return (stdout, stderr, code);
            }
            Ok(None) => {
                if start.elapsed() >= timeout {
                    child.kill().ok();
                    child.wait().ok();
                    return ("".to_string(), "timeout".to_string(), -1);
                }
                std::thread::sleep(poll_interval);
            }
            Err(_) => {
                return ("".to_string(), "process error".to_string(), -1);
            }
        }
    }
}

/// Test the /help command
#[test]
#[cfg(feature = "integration")]
fn test_interactive_help_command() {
    let (stdout, _stderr, _code) = run_interactive("/help\nexit\n", 30);

    // Should show help menu
    assert!(
        stdout.contains("/help") || stdout.contains("Commands:"),
        "Should display help. Got: {}",
        stdout
    );
}

/// Test the /status command
#[test]
#[cfg(feature = "integration")]
fn test_interactive_status_command() {
    let (stdout, _stderr, _code) = run_interactive("/status\nexit\n", 30);

    // Should show status info
    assert!(
        stdout.contains("Messages") || stdout.contains("Memory") || stdout.contains("tokens"),
        "Should display status. Got: {}",
        stdout
    );
}

/// Test the /memory command
#[test]
#[cfg(feature = "integration")]
fn test_interactive_memory_command() {
    let (stdout, _stderr, _code) = run_interactive("/memory\nexit\n", 30);

    // Should show memory stats
    assert!(
        stdout.contains("Memory") || stdout.contains("tokens") || stdout.contains("entries"),
        "Should display memory stats. Got: {}",
        stdout
    );
}

/// Test the /clear command
#[test]
#[cfg(feature = "integration")]
fn test_interactive_clear_command() {
    let (stdout, _stderr, _code) = run_interactive("/clear\nexit\n", 30);

    // Should confirm clearing
    assert!(
        stdout.contains("clear") || stdout.contains("Clear"),
        "Should confirm clearing. Got: {}",
        stdout
    );
}

/// Test the /tools command
#[test]
#[cfg(feature = "integration")]
fn test_interactive_tools_command() {
    let (stdout, stderr, _code) = run_interactive("/tools\nexit\n", 30);
    let combined = format!("{}{}", stdout, stderr);

    // Should list tools (file_read is a core tool) — check both stdout and stderr
    assert!(
        combined.contains("file_read") || combined.contains("directory_tree"),
        "Should list tools. Got stdout: {}, stderr: {}",
        stdout,
        stderr
    );
}

/// Test the /debug command when there is no active task history yet
#[test]
#[cfg(feature = "integration")]
fn test_interactive_debug_command_without_checkpoint() {
    let (stdout, stderr, _code) = run_interactive("/debug\nexit\n", 30);
    let combined = format!("{}{}", stdout, stderr);

    assert!(
        combined.contains("Execution Debug"),
        "Should show debug header. stdout: {}, stderr: {}",
        stdout,
        stderr
    );
    assert!(
        combined.contains("No active checkpoint/tool history for this session."),
        "Should explain there is no task history yet. stdout: {}, stderr: {}",
        stdout,
        stderr
    );
}

/// Test the extended debug commands when there is no active task history yet
#[test]
#[cfg(feature = "integration")]
fn test_interactive_extended_debug_commands_without_checkpoint() {
    let (stdout, stderr, _code) = run_interactive(
        "/debug full\n/debug tool 1\n/debug state\n/debug-log full\nexit\n",
        30,
    );
    let combined = format!("{}{}", stdout, stderr);

    assert!(
        combined.contains("Execution Debug"),
        "Should show execution debug output. stdout: {}, stderr: {}",
        stdout,
        stderr
    );
    assert!(
        combined.contains("No active checkpoint/tool history for this session."),
        "Should explain missing task history. stdout: {}, stderr: {}",
        stdout,
        stderr
    );
    assert!(
        combined.contains("Session Debug Log"),
        "Should show session log output. stdout: {}, stderr: {}",
        stdout,
        stderr
    );
    assert!(
        combined.contains("Task State"),
        "Should show task-state debug output. stdout: {}, stderr: {}",
        stdout,
        stderr
    );
}

/// Test queue management commands in interactive mode
#[test]
#[cfg(feature = "integration")]
fn test_interactive_queue_commands() {
    let input = concat!(
        "/queue first queued task\n",
        "/queue second queued task\n",
        "/queue list\n",
        "/queue drop 1\n",
        "/queue list\n",
        "/queue clear\n",
        "/queue list\n",
        "exit\n"
    );
    let (stdout, stderr, _code) = run_interactive(input, 30);
    let combined = format!("{}{}", stdout, stderr);

    assert!(
        combined.contains("Queued (1 pending)") && combined.contains("Queued (2 pending)"),
        "Should acknowledge queued messages. stdout: {}, stderr: {}",
        stdout,
        stderr
    );
    assert!(
        combined.contains("Queued messages (2):"),
        "Should list both queued messages. stdout: {}, stderr: {}",
        stdout,
        stderr
    );
    assert!(
        combined.contains("Removed message 1: first queued task"),
        "Should drop the first queued message. stdout: {}, stderr: {}",
        stdout,
        stderr
    );
    assert!(
        combined.contains("Queued messages (1):") && combined.contains("second queued task"),
        "Should keep the remaining queued message after drop. stdout: {}, stderr: {}",
        stdout,
        stderr
    );
    assert!(
        combined.contains("Cleared 1 queued message(s).") && combined.contains("Queue is empty."),
        "Should clear the queue and report empty state. stdout: {}, stderr: {}",
        stdout,
        stderr
    );
}

/// Test exit command
#[test]
#[cfg(feature = "integration")]
fn test_interactive_exit_command() {
    let (stdout, _stderr, code) = run_interactive("exit\n", 30);

    // Should exit cleanly
    assert!(
        code == 0 || stdout.contains("exit") || stdout.contains("Basic Mode"),
        "Should exit. Code: {}, stdout: {}",
        code,
        stdout
    );
}

/// Test quit command (alias for exit)
#[test]
#[cfg(feature = "integration")]
fn test_interactive_quit_command() {
    let (stdout, _stderr, code) = run_interactive("quit\n", 30);

    // Should exit cleanly
    assert!(
        code == 0 || stdout.contains("quit") || stdout.contains("Basic Mode"),
        "Should quit. Code: {}, stdout: {}",
        code,
        stdout
    );
}

/// Test fallback to basic mode when terminal unavailable
#[test]
#[cfg(feature = "integration")]
fn test_interactive_fallback_to_basic_mode() {
    let (stdout, stderr, _code) = run_interactive("exit\n", 30);

    // Should fall back to basic mode (since we're not in a real TTY)
    assert!(
        stdout.contains("Basic Mode")
            || stderr.contains("basic mode")
            || stderr.contains("falling back"),
        "Should fall back to basic mode. stdout: {}, stderr: {}",
        stdout,
        stderr
    );
}

/// Test the run command (non-interactive)
#[test]
#[cfg(feature = "integration")]
fn test_run_command_simple_task() {
    let (stdout, stderr, code) = run_task("echo hello", 60);

    // Should complete the task (output may appear in stdout or stderr depending on platform).
    // In CI environments without a local model, the process may time out — that's acceptable.
    let combined = format!("{}{}", stdout, stderr);
    assert!(
        code == 0
            || combined.contains("Task")
            || combined.contains("completed")
            || combined.contains("Tool")
            || combined.contains("hello")
            || combined.contains("timeout")
            || combined.contains("timed out")
            || code == -1,
        "Should run task or timeout gracefully. code: {}, stdout: {}, stderr: {}",
        code,
        stdout,
        stderr
    );
}

/// Test analyze command
#[test]
#[cfg(feature = "integration")]
fn test_analyze_command() {
    let output = Command::new(get_binary_path())
        .args(["analyze", "./src"])
        .output()
        .expect("Failed to run selfware");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    // Should analyze the directory
    assert!(
        stdout.contains("Surveying") || stdout.contains("directory") || stdout.contains("Tool"),
        "Should analyze directory. Got: {}",
        stdout
    );
}

/// Test --help flag
#[test]
#[cfg(feature = "integration")]
fn test_help_flag() {
    let output = Command::new(get_binary_path())
        .arg("--help")
        .output()
        .expect("Failed to run selfware");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    // Should show CLI help
    assert!(
        stdout.contains("Usage:") || stdout.contains("selfware"),
        "Should show help. Got: {}",
        stdout
    );
    assert!(stdout.contains("chat"), "Should list chat command");
    assert!(stdout.contains("run"), "Should list run command");
}

/// Test --version flag
#[test]
#[cfg(feature = "integration")]
fn test_version_flag() {
    let output = Command::new(get_binary_path())
        .arg("--version")
        .output()
        .expect("Failed to run selfware");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    // Should show version
    assert!(
        stdout.contains("selfware") || stdout.contains("0."),
        "Should show version. Got: {}",
        stdout
    );
}

/// Test journal command
#[test]
#[cfg(feature = "integration")]
fn test_journal_command() {
    let output = Command::new(get_binary_path())
        .arg("journal")
        .output()
        .expect("Failed to run selfware");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let code = output.status.code().unwrap_or(-1);

    // Should list journal entries (may be empty)
    assert!(
        code == 0 || stdout.contains("journal") || stdout.contains("No"),
        "Should handle journal. Code: {}, stdout: {}",
        code,
        stdout
    );
}

/// Test status command
#[test]
#[cfg(feature = "integration")]
fn test_status_command() {
    let output = Command::new(get_binary_path())
        .arg("status")
        .output()
        .expect("Failed to run selfware");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    // Should show status
    assert!(
        stdout.contains("WORKSHOP") || stdout.contains("status") || stdout.contains("Status"),
        "Should show status. Got: {}",
        stdout
    );
}

/// Test garden command
#[test]
#[cfg(feature = "integration")]
fn test_garden_command() {
    let output = Command::new(get_binary_path())
        .args(["garden", "."])
        .output()
        .expect("Failed to run selfware");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let code = output.status.code().unwrap_or(-1);

    // Should show garden view
    assert!(
        code == 0 || stdout.contains("garden") || stdout.contains("Garden"),
        "Should show garden. Code: {}, stdout: {}",
        code,
        stdout
    );
}

/// Test multi-chat command initialization
#[test]
#[cfg(feature = "integration")]
fn test_multi_chat_init() {
    let mut child = Command::new(get_binary_path())
        .args(["multi-chat", "-n", "2"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn selfware");

    // Send exit immediately
    if let Some(mut stdin) = child.stdin.take() {
        stdin.write_all(b"exit\n").ok();
    }

    let output = child.wait_with_output().expect("Failed to wait");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    // Should initialize multi-agent mode
    assert!(
        stdout.contains("concurrent") || stdout.contains("Multi") || stdout.contains("WORKSHOP"),
        "Should init multi-chat. Got: {}",
        stdout
    );
}

/// Test config file specification
#[test]
#[cfg(feature = "integration")]
fn test_config_flag() {
    let output = Command::new(get_binary_path())
        .args(["-c", "selfware.toml", "--help"])
        .output()
        .expect("Failed to run selfware");

    let code = output.status.code().unwrap_or(-1);

    // Should accept config flag
    assert!(code == 0, "Should accept config flag");
}

/// Test workdir flag
#[test]
#[cfg(feature = "integration")]
fn test_workdir_flag() {
    let tmp = std::env::temp_dir();
    let tmp_str = tmp.to_string_lossy();
    let output = Command::new(get_binary_path())
        .args(["-C", &tmp_str, "--help"])
        .output()
        .expect("Failed to run selfware");

    let code = output.status.code().unwrap_or(-1);

    // Should accept workdir flag
    assert!(code == 0, "Should accept workdir flag");
}

/// Test invalid command
#[test]
#[cfg(feature = "integration")]
fn test_invalid_command() {
    let output = Command::new(get_binary_path())
        .arg("invalid_command_xyz")
        .output()
        .expect("Failed to run selfware");

    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let code = output.status.code().unwrap_or(-1);

    // Should error on invalid command
    assert!(
        code != 0 || stderr.contains("error") || stderr.contains("invalid"),
        "Should reject invalid command. Code: {}",
        code
    );
}

/// Test quiet mode
#[test]
#[cfg(feature = "integration")]
fn test_quiet_mode() {
    let output = Command::new(get_binary_path())
        .args(["-q", "status"])
        .output()
        .expect("Failed to run selfware");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    // Quiet mode should have less output (no banner)
    // Note: This is a weak test, mainly checking it doesn't crash
    let _ = stdout;
}

/// Test Ctrl+C handling (interrupt)
#[test]
#[cfg(feature = "integration")]
fn test_interrupt_handling() {
    // This tests that the process can be killed cleanly
    let mut child = Command::new(get_binary_path())
        .arg("chat")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn selfware");

    // Give it a moment to start
    std::thread::sleep(Duration::from_millis(500));

    // Kill it
    child.kill().ok();
    let status = child.wait().expect("Failed to wait");

    // Should be killed (not crash)
    assert!(
        !status.success() || status.code().is_some(),
        "Process should be killable"
    );
}

/// Test that binary exists and is executable
#[test]
#[cfg(feature = "integration")]
fn test_binary_exists() {
    let binary_path = get_binary_path();
    let path = std::path::Path::new(&binary_path);
    assert!(
        path.exists(),
        "Binary should exist at {} (run: cargo test to build)",
        binary_path
    );
}

/// Test environment variable configuration
#[test]
#[cfg(feature = "integration")]
fn test_env_var_config() {
    let output = Command::new(get_binary_path())
        .env("SELFWARE_DEBUG", "1")
        .arg("--help")
        .output()
        .expect("Failed to run selfware");

    let code = output.status.code().unwrap_or(-1);

    // Should accept env var
    assert!(code == 0, "Should work with env var");
}

/// Test --output-format json produces valid JSON
#[test]
#[cfg(feature = "integration")]
fn test_output_format_json() {
    let output = Command::new(get_binary_path())
        .args(["status", "--output-format", "json"])
        .output()
        .expect("Failed to run selfware");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let code = output.status.code().unwrap_or(-1);

    assert!(code == 0, "Should exit successfully");

    // Output should be valid JSON
    let parsed: Result<serde_json::Value, _> = serde_json::from_str(&stdout);
    assert!(
        parsed.is_ok(),
        "Output should be valid JSON. Got: {}",
        stdout
    );

    // JSON should contain expected fields
    let json = parsed.unwrap();
    assert!(
        json.get("model").is_some(),
        "JSON should have 'model' field"
    );
    assert!(
        json.get("journal").is_some(),
        "JSON should have 'journal' field"
    );
}

/// Test --no-color disables color codes
#[test]
#[cfg(feature = "integration")]
fn test_no_color_flag() {
    let output = Command::new(get_binary_path())
        .args(["--no-color", "status"])
        .output()
        .expect("Failed to run selfware");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    // Should not contain ANSI escape codes
    assert!(
        !stdout.contains("\x1b["),
        "Output should not contain ANSI escape codes with --no-color"
    );
}

/// Test NO_COLOR env var disables color codes
#[test]
#[cfg(feature = "integration")]
fn test_no_color_env_var() {
    let output = Command::new(get_binary_path())
        .env("NO_COLOR", "1")
        .arg("status")
        .output()
        .expect("Failed to run selfware");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();

    // Should not contain ANSI escape codes
    assert!(
        !stdout.contains("\x1b["),
        "Output should not contain ANSI escape codes with NO_COLOR env var"
    );
}

/// Test SELFWARE_TIMEOUT env var is applied
#[test]
#[cfg(feature = "integration")]
fn test_selfware_timeout_env_var() {
    // This just checks the env var is accepted without error
    // Actual timeout behavior is hard to test without a slow endpoint
    let output = Command::new(get_binary_path())
        .env("SELFWARE_TIMEOUT", "120")
        .arg("--help")
        .output()
        .expect("Failed to run selfware");

    let code = output.status.code().unwrap_or(-1);
    assert!(code == 0, "Should accept SELFWARE_TIMEOUT env var");
}

/// Test that non-interactive mode fails fast without recovery loop when confirmation is required
/// This validates the AgentError::ConfirmationRequired path
/// Note: Model-dependent test - may be flaky if model doesn't call confirmation-required tools
#[test]
#[ignore] // Model-dependent: run with --include-ignored for E2E coverage
#[cfg(feature = "integration")]
fn test_non_interactive_fails_fast_on_confirmation() {
    // Run without --yolo, piping empty stdin to ensure non-interactive mode
    let mut child = Command::new(get_binary_path())
        .args(["run", "use shell_exec to run pwd"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn selfware");

    // Close stdin immediately to simulate non-interactive
    drop(child.stdin.take());

    let timeout = Duration::from_secs(60);
    let start = Instant::now();

    loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                let mut stdout_buf = Vec::new();
                let mut stderr_buf = Vec::new();
                if let Some(mut stdout) = child.stdout.take() {
                    use std::io::Read;
                    stdout.read_to_end(&mut stdout_buf).ok();
                }
                if let Some(mut stderr) = child.stderr.take() {
                    use std::io::Read;
                    stderr.read_to_end(&mut stderr_buf).ok();
                }
                let stdout = String::from_utf8_lossy(&stdout_buf);
                let stderr = String::from_utf8_lossy(&stderr_buf);
                let combined = format!("{}{}", stdout, stderr);

                // Should fail (non-zero exit code)
                assert!(
                    !status.success(),
                    "Non-interactive mode should fail when confirmation required"
                );

                // Should mention confirmation/non-interactive in output
                assert!(
                    combined.contains("confirmation")
                        || combined.contains("non-interactive")
                        || combined.contains("--yolo"),
                    "Error should mention confirmation issue. Output: {}",
                    combined
                );

                // Should NOT show multiple recovery attempts
                let recovery_count = combined.matches("Recovering from error").count();
                assert!(
                    recovery_count == 0,
                    "Should fail immediately without recovery loop, but found {} recovery attempts",
                    recovery_count
                );

                return;
            }
            Ok(None) => {
                if start.elapsed() >= timeout {
                    child.kill().ok();
                    panic!("Test timed out - possible infinite loop in error handling");
                }
                std::thread::sleep(Duration::from_millis(100));
            }
            Err(e) => panic!("Error waiting for process: {}", e),
        }
    }
}