start-command 0.15.0

Gamification of coding, execute any command with ability to auto-report issues on GitHub
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
//! start-command CLI
//!
//! A command-line tool for executing commands with:
//! - Natural language command aliases (via substitutions.lino)
//! - Process isolation (screen, tmux, docker, ssh)
//! - User isolation (run as separate user)
//! - Automatic failure reporting (GitHub issues)

use std::env;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use std::process::{self, Command, Stdio};

use start_command::{
    append_log_file,
    args_parser::{
        generate_session_name, generate_uuid, get_effective_mode, has_isolation, parse_args,
    },
    clear_current_execution, create_finish_block, create_log_footer, create_log_header,
    create_log_path_for_execution, create_start_block,
    execution_control::{control_execution, ControlAction},
    execution_store::{
        CleanupOptions, ExecutionRecord, ExecutionRecordOptions, ExecutionStore,
        ExecutionStoreOptions,
    },
    failure_handler::{handle_failure, Config as FailureConfig},
    get_timestamp,
    isolation::{run_as_isolated_user, run_isolated, IsolationOptions},
    output_blocks::{FinishBlockOptions, StartBlockOptions},
    set_current_execution, setup_signal_handlers,
    status_formatter::{list_executions, query_status},
    substitution::{process_command, ProcessOptions},
    upload_execution_log,
    usage::print_usage,
    user_manager::{
        create_isolated_user, delete_user, get_current_user_groups, has_sudo_access,
        CreateIsolatedUserOptions, DeleteUserOptions,
    },
    write_log_file, LogHeaderParams,
};

/// Configuration from environment variables
struct Config {
    /// Disable automatic issue creation
    disable_auto_issue: bool,
    /// Disable log upload
    disable_log_upload: bool,
    /// Verbose mode
    verbose: bool,
    /// Disable substitutions/aliases
    disable_substitutions: bool,
    /// Custom substitutions file path
    substitutions_path: Option<String>,
    /// Use command-stream library for execution
    use_command_stream: bool,
    /// Disable execution tracking
    disable_tracking: bool,
    /// Custom app folder for execution tracking
    app_folder: Option<String>,
}

impl Config {
    fn from_env() -> Self {
        // Default app folder to ~/.start-command
        let default_app_folder =
            dirs::home_dir().map(|h| h.join(".start-command").to_string_lossy().to_string());

        Self {
            disable_auto_issue: env_bool("START_DISABLE_AUTO_ISSUE"),
            disable_log_upload: env_bool("START_DISABLE_LOG_UPLOAD"),
            verbose: env_bool("START_VERBOSE"),
            disable_substitutions: env_bool("START_DISABLE_SUBSTITUTIONS"),
            substitutions_path: env::var("START_SUBSTITUTIONS_PATH").ok(),
            use_command_stream: env_bool("START_USE_COMMAND_STREAM"),
            disable_tracking: env_bool("START_DISABLE_TRACKING"),
            app_folder: env::var("START_APP_FOLDER").ok().or(default_app_folder),
        }
    }

    /// Create an execution store based on config
    fn create_execution_store(&self) -> Option<ExecutionStore> {
        if self.disable_tracking {
            return None;
        }

        let options = ExecutionStoreOptions {
            verbose: self.verbose,
            app_folder: self.app_folder.as_ref().map(PathBuf::from),
            ..ExecutionStoreOptions::default()
        };

        Some(ExecutionStore::with_options(options))
    }
}

fn env_bool(name: &str) -> bool {
    env::var(name).is_ok_and(|v| v == "1" || v == "true")
}

fn main() {
    // Set up signal handlers for graceful cleanup on interruption
    setup_signal_handlers();

    let config = Config::from_env();
    let args: Vec<String> = env::args().skip(1).collect();

    // Handle --version flag
    let has_version_flag = !args.is_empty() && (args[0] == "--version" || args[0] == "-v");
    let has_verbose_with_version =
        has_version_flag && args.iter().any(|a| a == "--verbose" || a == "--debug");

    let version_related_args = ["--version", "-v", "--", "--verbose", "--debug"];
    let is_version_only = has_version_flag
        && args
            .iter()
            .all(|a| version_related_args.contains(&a.as_str()) || *a == args[0]);

    if has_version_flag && is_version_only {
        print_version(has_verbose_with_version || config.verbose);
        process::exit(0);
    }

    if args.is_empty() {
        print_usage();
        process::exit(0);
    }

    // Parse wrapper options and command
    let parsed = match parse_args(&args) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("Error: {}", e);
            process::exit(1);
        }
    };

    let wrapper_options = parsed.wrapper_options;
    let parsed_command = parsed.command.clone();

    if let Some(ref uuid) = wrapper_options.status {
        handle_status_query(&config, uuid, wrapper_options.output_format.as_deref());
        process::exit(0);
    }

    if wrapper_options.list {
        handle_list_query(&config, wrapper_options.output_format.as_deref());
        process::exit(0);
    }

    if let Some(ref identifier) = wrapper_options.upload_log {
        process::exit(handle_upload_log_query(&config, identifier));
    }

    if let Some(ref identifier) = wrapper_options.stop {
        handle_control_query(&config, identifier, ControlAction::Stop);
        process::exit(0);
    }

    if let Some(ref identifier) = wrapper_options.terminate {
        handle_control_query(&config, identifier, ControlAction::Terminate);
        process::exit(0);
    }

    if wrapper_options.cleanup {
        handle_cleanup(&config, wrapper_options.cleanup_dry_run);
        process::exit(0);
    }

    // Check if no command was provided
    if parsed_command.is_empty() {
        eprintln!("Error: No command provided");
        print_usage();
        process::exit(1);
    }

    // Process through substitution engine (unless disabled)
    let mut command = parsed_command.clone();
    let mut substitution_result = None;

    if !config.disable_substitutions {
        let result = process_command(
            &parsed_command,
            &ProcessOptions {
                custom_lino_path: config.substitutions_path.clone(),
                verbose: config.verbose,
            },
        );

        if result.matched {
            command = result.command.clone();
            if config.verbose {
                println!("[Substitution] \"{}\" -> \"{}\"", parsed_command, command);
                println!();
            }
            substitution_result = Some(result);
        }
    }

    // Determine if we should use command-stream
    let use_command_stream = wrapper_options.use_command_stream || config.use_command_stream;

    // Generate session ID if not provided (auto-generate UUID)
    let session_id = wrapper_options
        .session_id
        .clone()
        .unwrap_or_else(generate_uuid);

    // Main execution
    if has_isolation(&wrapper_options) || wrapper_options.user {
        run_with_isolation(
            &config,
            &wrapper_options,
            &command,
            use_command_stream,
            &session_id,
        );
    } else {
        run_direct(
            &config,
            &command,
            &parsed_command,
            substitution_result.as_ref(),
            &session_id,
        );
    }
}

/// Print version information
fn print_version(verbose: bool) {
    let version = env!("CARGO_PKG_VERSION");
    println!("start-command version: {} (Rust)", version);
    println!();

    println!("OS: {}", std::env::consts::OS);
    println!("Architecture: {}", std::env::consts::ARCH);
    println!();

    // Check for installed isolation tools
    println!("Isolation tools:");

    if verbose {
        println!("[verbose] Checking isolation tools...");
    }

    // Check screen
    if let Some(version) = get_tool_version("screen", "-v", verbose) {
        println!("  screen: {}", version);
    } else {
        println!("  screen: not installed");
    }

    // Check tmux
    if let Some(version) = get_tool_version("tmux", "-V", verbose) {
        println!("  tmux: {}", version);
    } else {
        println!("  tmux: not installed");
    }

    // Check docker
    if let Some(version) = get_tool_version("docker", "--version", verbose) {
        println!("  docker: {}", version);
    } else {
        println!("  docker: not installed");
    }
}

/// Get version of an installed tool
fn get_tool_version(tool_name: &str, version_flag: &str, verbose: bool) -> Option<String> {
    let which_cmd = if cfg!(windows) { "where" } else { "which" };

    // Check if tool exists
    let exists = Command::new(which_cmd)
        .arg(tool_name)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false);

    if !exists {
        if verbose {
            println!("[verbose] {}: not found in PATH", tool_name);
        }
        return None;
    }

    // Get version
    let output = Command::new(tool_name).arg(version_flag).output().ok()?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let combined = format!("{}{}", stdout, stderr).trim().to_string();

    if verbose {
        println!(
            "[verbose] {} {}: exit={}, output=\"{}\"",
            tool_name,
            version_flag,
            output.status.code().unwrap_or(-1),
            &combined[..100.min(combined.len())]
        );
    }

    if combined.is_empty() {
        return None;
    }

    combined.lines().next().map(String::from)
}

/// Handle status query
fn handle_status_query(config: &Config, uuid: &str, output_format: Option<&str>) {
    let store = config.create_execution_store();
    let result = query_status(store.as_ref(), uuid, output_format);

    if result.success {
        if let Some(output) = result.output {
            println!("{}", output);
        }
    } else {
        if let Some(error) = result.error {
            eprintln!("Error: {}", error);
        }
        process::exit(1);
    }
}

/// Handle list query
fn handle_list_query(config: &Config, output_format: Option<&str>) {
    let store = config.create_execution_store();
    let result = list_executions(store.as_ref(), output_format);

    if result.success {
        if let Some(output) = result.output {
            println!("{}", output);
        }
    } else {
        if let Some(error) = result.error {
            eprintln!("Error: {}", error);
        }
        process::exit(1);
    }
}

/// Handle upload-log query
fn handle_upload_log_query(config: &Config, identifier: &str) -> i32 {
    let store = config.create_execution_store();
    match upload_execution_log(store.as_ref(), identifier) {
        Ok(code) => code,
        Err(error) => {
            eprintln!("Error: {}", error);
            1
        }
    }
}

/// Handle detached execution control query
fn handle_control_query(config: &Config, identifier: &str, action: ControlAction) {
    let store = config.create_execution_store();
    let result = control_execution(store.as_ref(), identifier, action);

    if result.success {
        if let Some(output) = result.output {
            println!("{}", output);
        }
    } else {
        if let Some(error) = result.error {
            eprintln!("Error: {}", error);
        }
        process::exit(1);
    }
}

/// Handle --cleanup flag
/// Cleans up stale "executing" records (processes that crashed or were killed)
fn handle_cleanup(config: &Config, dry_run: bool) {
    let store = match config.create_execution_store() {
        Some(s) => s,
        None => {
            eprintln!("Error: Execution tracking is disabled.");
            process::exit(1);
        }
    };

    let result = store.cleanup_stale(CleanupOptions {
        dry_run,
        ..Default::default()
    });

    // Print any errors
    for error in &result.errors {
        eprintln!("Error: {}", error);
    }

    if result.records.is_empty() {
        println!("No stale records found.");
        return;
    }

    if dry_run {
        println!(
            "Found {} stale record(s) that would be cleaned up:\n",
            result.records.len()
        );
    } else {
        println!("Cleaned up {} stale record(s):\n", result.cleaned);
    }

    for record in &result.records {
        // Parse start time for display
        let start_time_display = chrono::DateTime::parse_from_rfc3339(&record.start_time)
            .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
            .unwrap_or_else(|_| record.start_time.clone());

        println!("  UUID: {}", record.uuid);
        println!("  Command: {}", record.command);
        println!("  Started: {}", start_time_display);
        println!(
            "  PID: {}",
            record
                .pid
                .map(|p| p.to_string())
                .unwrap_or("N/A".to_string())
        );
        println!();
    }

    if dry_run {
        println!("Run with --cleanup to actually clean up these records.");
    }
}

/// Run command with isolation
fn run_with_isolation(
    config: &Config,
    wrapper_options: &start_command::WrapperOptions,
    command: &str,
    _use_command_stream: bool,
    session_id: &str,
) {
    let environment = wrapper_options.isolated.as_deref();
    let mode = get_effective_mode(wrapper_options);
    let start_time = get_timestamp();
    let start_instant = std::time::Instant::now();

    // Docker image is now set in validate_options (defaults to OS-matched image)
    let effective_image = wrapper_options.image.clone();
    let log_file_path = create_log_path_for_execution(environment.unwrap_or("direct"), session_id);
    let session_name = wrapper_options
        .session
        .clone()
        .unwrap_or_else(|| generate_session_name(Some(environment.unwrap_or("start"))));
    let mut extra_lines: Vec<String> = Vec::new();
    let mut created_user: Option<String> = None;

    if wrapper_options.user {
        // Check for sudo access
        if !has_sudo_access() {
            eprintln!("Error: --isolated-user requires sudo access without password.");
            eprintln!("Configure NOPASSWD in sudoers or run with appropriate permissions.");
            process::exit(1);
        }

        // Get current user groups
        let current_groups = get_current_user_groups();
        let important_groups: Vec<&str> = ["sudo", "docker", "wheel", "admin"]
            .iter()
            .copied()
            .filter(|g| current_groups.iter().any(|cg| cg == *g))
            .collect();

        extra_lines.push("[User Isolation] Creating new user...".to_string());
        if !important_groups.is_empty() {
            extra_lines.push(format!(
                "[User Isolation] Inheriting groups: {}",
                important_groups.join(", ")
            ));
        }

        // Create the isolated user
        let user_result = create_isolated_user(
            wrapper_options.user_name.as_deref(),
            &CreateIsolatedUserOptions::default(),
        );

        if !user_result.success {
            eprintln!(
                "Error: Failed to create isolated user: {}",
                user_result.message
            );
            process::exit(1);
        }

        let username = user_result.username.unwrap();
        extra_lines.push(format!("[User Isolation] Created user: {}", username));
        if let Some(groups) = &user_result.groups {
            if !groups.is_empty() {
                extra_lines.push(format!(
                    "[User Isolation] User groups: {}",
                    groups.join(", ")
                ));
            }
        }
        if wrapper_options.keep_user {
            extra_lines.push("[User Isolation] User will be kept after completion".to_string());
        }

        created_user = Some(username);
    }

    // Add isolation info to extra lines (session name for reconnecting, see issue #67)
    if let Some(env) = environment {
        extra_lines.push(format!("[Isolation] Environment: {}, Mode: {}", env, mode));
        extra_lines.push(format!("[Isolation] Session: {}", session_name));
    }
    if let Some(ref image) = effective_image {
        extra_lines.push(format!("[Isolation] Image: {}", image));
    }
    if let Some(ref endpoint) = wrapper_options.endpoint {
        extra_lines.push(format!("[Isolation] Endpoint: {}", endpoint));
    }
    if let Some(ref user) = created_user {
        extra_lines.push(format!("[Isolation] User: {} (isolated)", user));
    }

    // Print start block with session ID and isolation info
    // For Docker isolation, defer the command display since virtual commands may be shown first
    let is_docker_isolation = environment == Some("docker");
    let extra_lines_refs: Vec<&str> = extra_lines.iter().map(|s| s.as_str()).collect();
    println!(
        "{}",
        create_start_block(&StartBlockOptions {
            session_id,
            timestamp: &start_time,
            command,
            extra_lines: if extra_lines.is_empty() {
                None
            } else {
                Some(extra_lines_refs)
            },
            style: None,
            width: None,
            defer_command: is_docker_isolation,
        })
    );
    // Only print empty line when not deferring command (docker isolation handles its own spacing)
    if !is_docker_isolation {
        println!();
    }

    // Create log header
    let mut log_content = create_log_header(&LogHeaderParams {
        command: command.to_string(),
        environment: environment.unwrap_or("direct").to_string(),
        mode: mode.to_string(),
        session_name: session_name.clone(),
        image: effective_image.clone(),
        user: created_user.clone(),
        start_time: start_time.clone(),
    });

    // Create execution tracking record with isolation options
    let execution_store = config.create_execution_store();
    let mut opts_map: std::collections::HashMap<String, serde_json::Value> =
        std::collections::HashMap::new();
    let str_val = |s: &str| serde_json::Value::String(s.to_string());
    if let Some(env) = environment {
        opts_map.insert("isolated".into(), str_val(env));
    }
    opts_map.insert("isolationMode".into(), str_val(mode));
    opts_map.insert("sessionName".into(), str_val(&session_name));
    if let Some(ref v) = effective_image {
        opts_map.insert("image".into(), str_val(v));
    }
    if let Some(ref v) = wrapper_options.endpoint {
        opts_map.insert("endpoint".into(), str_val(v));
    }
    if let Some(ref v) = created_user {
        opts_map.insert("user".into(), str_val(v));
    }
    opts_map.insert(
        "keepAlive".into(),
        serde_json::Value::Bool(wrapper_options.keep_alive),
    );
    let mut execution_record = ExecutionRecord::with_options(ExecutionRecordOptions {
        uuid: Some(session_id.to_string()),
        command: command.to_string(),
        log_path: Some(log_file_path.to_string_lossy().to_string()),
        pid: Some(process::id()),
        options: Some(opts_map),
        ..Default::default()
    });
    if let Some(ref store) = execution_store {
        match store.save(&execution_record) {
            Err(e) if config.verbose => {
                eprintln!(
                    "[ExecutionStore] Warning: Failed to save initial record: {}",
                    e
                );
            }
            Ok(()) => {
                if config.verbose {
                    println!("[ExecutionStore] Execution ID: {}", execution_record.uuid);
                }
                set_current_execution(execution_record.clone(), store.clone());
            }
            _ => {}
        }
    }
    log_content = log_content.replacen(
        "=== Start Command Log ===\n",
        &format!(
            "=== Start Command Log ===\nExecution ID: {}\n",
            execution_record.uuid
        ),
        1,
    );
    write_log_file(&log_file_path, &log_content);

    let result = if let Some(env) = environment {
        // Run in isolation backend
        let options = IsolationOptions {
            session: Some(session_name.clone()),
            image: effective_image.clone(),
            endpoint: wrapper_options.endpoint.clone(),
            detached: mode == "detached",
            user: created_user.clone(),
            keep_alive: wrapper_options.keep_alive,
            auto_remove_docker_container: wrapper_options.auto_remove_docker_container,
            shell: wrapper_options.shell.clone(),
            log_path: Some(log_file_path.clone()),
        };
        run_isolated(env, command, &options)
    } else if let Some(ref user) = created_user {
        // Run directly as the created user
        run_as_isolated_user(command, user)
    } else {
        // This shouldn't happen
        start_command::IsolationResult {
            success: false,
            message: "No isolation configuration provided".to_string(),
            ..Default::default()
        }
    };

    // Get exit code
    let exit_code = result
        .exit_code
        .unwrap_or(if result.success { 0 } else { 1 });
    let end_time = get_timestamp();

    if mode == "detached" && result.success {
        append_log_file(&log_file_path, &format!("{}\n", result.message));
    } else {
        append_log_file(&log_file_path, &format!("{}\n", result.message));
        append_log_file(&log_file_path, &create_log_footer(&end_time, exit_code));
    }

    // Update execution record: detached keeps "executing" (resolved at query time)
    if let Some(ref store) = execution_store {
        if let Some(container_id) = result.container_id.clone() {
            execution_record.options.insert(
                "containerId".to_string(),
                serde_json::Value::String(container_id),
            );
        }
        if mode != "detached" {
            execution_record.complete(exit_code);
        }
        if let Err(e) = store.save(&execution_record) {
            if config.verbose {
                eprintln!("[ExecutionStore] Warning: Failed to update record: {}", e);
            }
        }
        clear_current_execution();
    }

    // Cleanup: delete the created user if we created one (unless --keep-user)
    // This output goes to stdout but NOT inside the boxes - it's operational info
    if let Some(ref user) = created_user {
        if !wrapper_options.keep_user {
            println!("[User Isolation] Cleaning up user: {}", user);
            let delete_result = delete_user(user, &DeleteUserOptions { remove_home: true });
            if delete_result.success {
                println!("[User Isolation] User deleted successfully");
            } else {
                println!("[User Isolation] Warning: {}", delete_result.message);
            }
            println!();
        } else {
            println!(
                "[User Isolation] Keeping user: {} (use 'sudo userdel -r {}' to delete)",
                user, user
            );
            println!();
        }
    }

    // Print finish block with result message inside
    // Add empty line before finish block for visual separation
    println!();
    let duration_ms = start_instant.elapsed().as_secs_f64() * 1000.0;
    // Convert extra_lines to &str references for the finish block
    let extra_lines_refs: Vec<&str> = extra_lines.iter().map(|s| s.as_str()).collect();
    println!(
        "{}",
        create_finish_block(&FinishBlockOptions {
            session_id,
            timestamp: &end_time,
            exit_code,
            log_path: &log_file_path.to_string_lossy(),
            duration_ms: Some(duration_ms),
            result_message: Some(&result.message),
            extra_lines: Some(extra_lines_refs),
            style: None,
            width: None,
        })
    );

    process::exit(exit_code);
}

/// Run command directly (without isolation)
fn run_direct(
    config: &Config,
    command: &str,
    parsed_command: &str,
    substitution_result: Option<&start_command::SubstitutionResult>,
    session_id: &str,
) {
    let start_time = get_timestamp();
    let start_instant = std::time::Instant::now();

    // Determine display command (show substitution if applied)
    let display_command = if let Some(sub) = substitution_result {
        if sub.matched {
            format!("{} -> {}", parsed_command, command)
        } else {
            command.to_string()
        }
    } else {
        command.to_string()
    };

    // Print start block with session ID (no extra lines for direct execution)
    println!(
        "{}",
        create_start_block(&StartBlockOptions {
            session_id,
            timestamp: &start_time,
            command: &display_command,
            extra_lines: None,
            style: None,
            width: None,
            defer_command: false,
        })
    );
    println!();
    let command_name = command.split_whitespace().next().unwrap_or(command);

    // Determine shell
    let is_windows = cfg!(windows);
    let shell = if is_windows {
        "powershell.exe".to_string()
    } else {
        env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string())
    };
    let shell_args: Vec<&str> = if is_windows {
        vec!["-Command", command]
    } else {
        vec!["-c", command]
    };

    let log_file_path = create_log_path_for_execution("direct", session_id);

    let mut log_content = String::new();

    // Create execution tracking record with provided session ID
    let execution_store = config.create_execution_store();
    let mut execution_record = ExecutionRecord::with_options(ExecutionRecordOptions {
        uuid: Some(session_id.to_string()),
        command: command.to_string(),
        log_path: Some(log_file_path.to_string_lossy().to_string()),
        pid: Some(process::id()),
        ..Default::default()
    });

    // Save initial execution record and set up signal cleanup
    if let Some(ref store) = execution_store {
        if let Err(e) = store.save(&execution_record) {
            if config.verbose {
                eprintln!(
                    "[ExecutionStore] Warning: Failed to save initial record: {}",
                    e
                );
            }
        } else {
            if config.verbose {
                println!("[ExecutionStore] Execution ID: {}", execution_record.uuid);
            }
            // Set up global state for signal cleanup
            // Clone the store since we need to pass it to the signal handler
            set_current_execution(execution_record.clone(), store.clone());
        }
    }

    // Log header
    log_content.push_str("=== Start Command Log ===\n");
    log_content.push_str(&format!("Timestamp: {}\n", start_time));
    if let Some(sub) = substitution_result {
        if sub.matched {
            log_content.push_str(&format!("Original Input: {}\n", parsed_command));
            log_content.push_str(&format!("Substituted Command: {}\n", command));
            if let Some(ref rule) = sub.rule {
                log_content.push_str(&format!("Pattern Matched: {}\n", rule.pattern));
            }
        }
    } else {
        log_content.push_str(&format!("Command: {}\n", command));
    }
    log_content.push_str(&format!("Shell: {}\n", shell));
    log_content.push_str(&format!("Platform: {}\n", std::env::consts::OS));
    log_content.push_str(&format!(
        "Working Directory: {}\n",
        env::current_dir().unwrap_or_default().display()
    ));
    log_content.push_str(&format!("{}\n\n", "=".repeat(50)));
    write_log_file(&log_file_path, &log_content);

    // Execute the command with piped stdout/stderr so we can capture and display output
    // Using spawn() instead of output() to stream data in real-time (Issue #57)
    let mut child = match Command::new(&shell)
        .args(&shell_args)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
    {
        Ok(child) => child,
        Err(e) => {
            let error_msg = format!("Error executing command: {}", e);
            log_content.push_str(&format!("\n{}\n", error_msg));
            eprintln!("\n{}", error_msg);

            let end_time = get_timestamp();
            log_content.push_str(&format!("\n{}\n", "=".repeat(50)));
            log_content.push_str(&format!("Finished: {}\n", end_time));
            log_content.push_str("Exit Code: 1\n");

            write_log_file(&log_file_path, &log_content);

            let duration_ms = start_instant.elapsed().as_secs_f64() * 1000.0;
            println!();
            println!(
                "{}",
                create_finish_block(&FinishBlockOptions {
                    session_id,
                    timestamp: &end_time,
                    exit_code: 1,
                    log_path: &log_file_path.to_string_lossy(),
                    duration_ms: Some(duration_ms),
                    result_message: None,
                    extra_lines: None,
                    style: None,
                    width: None,
                })
            );

            process::exit(1);
        }
    };

    // Read stdout and stderr, displaying and capturing in real-time
    // Use threads to read both streams concurrently to avoid deadlocks
    let stdout = child.stdout.take();
    let stderr = child.stderr.take();

    let stdout_log_path = log_file_path.clone();
    let stdout_handle = std::thread::spawn(move || {
        let mut output = String::new();
        if let Some(stdout) = stdout {
            let reader = BufReader::new(stdout);
            for line in reader.lines().map_while(Result::ok) {
                println!("{}", line);
                append_log_file(&stdout_log_path, &format!("{}\n", line));
                output.push_str(&line);
                output.push('\n');
            }
        }
        output
    });

    let stderr_log_path = log_file_path.clone();
    let stderr_handle = std::thread::spawn(move || {
        let mut output = String::new();
        if let Some(stderr) = stderr {
            let reader = BufReader::new(stderr);
            for line in reader.lines().map_while(Result::ok) {
                eprintln!("{}", line);
                append_log_file(&stderr_log_path, &format!("{}\n", line));
                output.push_str(&line);
                output.push('\n');
            }
        }
        output
    });

    // Wait for output threads to complete
    let stdout_output = stdout_handle.join().unwrap_or_default();
    let stderr_output = stderr_handle.join().unwrap_or_default();

    // Wait for child process to exit
    let exit_code = match child.wait() {
        Ok(status) => status.code().unwrap_or(1),
        Err(e) => {
            let error_msg = format!("Error waiting for command: {}", e);
            log_content.push_str(&format!("\n{}\n", error_msg));
            append_log_file(&log_file_path, &format!("\n{}\n", error_msg));
            eprintln!("\n{}", error_msg);
            1
        }
    };

    // Add captured output to log content
    if !stdout_output.is_empty() {
        log_content.push_str(&stdout_output);
    }
    if !stderr_output.is_empty() {
        log_content.push_str(&stderr_output);
    }

    let end_time = get_timestamp();

    // Log footer
    log_content.push_str(&format!("\n{}\n", "=".repeat(50)));
    log_content.push_str(&format!("Finished: {}\n", end_time));
    log_content.push_str(&format!("Exit Code: {}\n", exit_code));

    append_log_file(
        &log_file_path,
        &format!(
            "\n{}\nFinished: {}\nExit Code: {}\n",
            "=".repeat(50),
            end_time,
            exit_code
        ),
    );

    // Print finish block (no result_message for direct execution)
    let duration_ms = start_instant.elapsed().as_secs_f64() * 1000.0;
    println!();
    println!(
        "{}",
        create_finish_block(&FinishBlockOptions {
            session_id,
            timestamp: &end_time,
            exit_code,
            log_path: &log_file_path.to_string_lossy(),
            duration_ms: Some(duration_ms),
            result_message: None,
            extra_lines: None,
            style: None,
            width: None,
        })
    );

    // Update execution record with completion status
    if let Some(ref store) = execution_store {
        execution_record.complete(exit_code);
        if let Err(e) = store.save(&execution_record) {
            if config.verbose {
                eprintln!(
                    "[ExecutionStore] Warning: Failed to save completion record: {}",
                    e
                );
            }
        }
        // Clear the global signal cleanup state since we handled completion normally
        clear_current_execution();
    }

    // If command failed, try to auto-report
    if exit_code != 0 {
        handle_failure(
            &FailureConfig {
                disable_auto_issue: config.disable_auto_issue,
                disable_log_upload: config.disable_log_upload,
                verbose: config.verbose,
            },
            command_name,
            command,
            exit_code,
            &log_file_path.to_string_lossy(),
        );
    }

    process::exit(exit_code);
}