start-command 0.17.5

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
//! Status formatter module for execution records
//!
//! Provides formatting functions for execution status output in various formats:
//! - Links Notation (links-notation): Structured link doublet format with nested options
//! - JSON: Standard JSON output
//! - Text: Human-readable text format

use crate::docker_cleanup::docker_command;
use crate::execution_control::collect_process_ids;
use crate::execution_store::{ExecutionRecord, ExecutionStatus, ExecutionStore};
use crate::output_blocks::{escape_for_links_notation, format_value_for_links_notation};
use serde_json::Value;
use std::fs;
use std::io::{Read, Seek, SeekFrom};
use std::process::Command;

/// Live state of a detached docker container by name.
#[derive(Clone, Copy)]
struct DockerState {
    running: bool,
    exit_code: Option<i32>,
    oom_killed: Option<bool>,
}

/// Inspect the live state of a detached docker container by name.
///
/// Distinguishes "running", "stopped (with a real exit code)", and "cannot be
/// inspected at all". The last case matters on slow Docker-in-Docker hosts
/// (issue #136): right after `docker run -d` returns, `docker inspect <name>`
/// can transiently fail because the container is not visible yet. A failed
/// inspect must NOT be read as "stopped"; it means "unknown", so callers can
/// keep the session running instead of fabricating a terminal `-1` result.
///
/// Returns None when the container cannot be inspected (not found yet, removed,
/// or docker error).
fn inspect_docker_state(session_name: &str) -> Option<DockerState> {
    let output = Command::new(docker_command())
        .args([
            "inspect",
            "-f",
            "{{.State.Running}} {{.State.ExitCode}} {{.State.OOMKilled}}",
            session_name,
        ])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    let trimmed = stdout.trim();
    if trimmed.is_empty() {
        return None;
    }
    let mut parts = trimmed.split_whitespace();
    let running = parts.next() == Some("true");
    let exit_code = parts.next().and_then(|value| value.parse::<i32>().ok());
    let oom_killed = parts.next().and_then(|value| match value {
        "true" => Some(true),
        "false" => Some(false),
        _ => None,
    });
    Some(DockerState {
        running,
        exit_code,
        oom_killed,
    })
}

fn is_detached_docker_record(record: &ExecutionRecord) -> bool {
    record.options.get("isolated").and_then(|v| v.as_str()) == Some("docker")
        && record.options.get("isolationMode").and_then(|v| v.as_str()) == Some("detached")
        && record
            .options
            .get("sessionName")
            .and_then(|v| v.as_str())
            .is_some()
}

fn read_docker_state(record: &ExecutionRecord) -> Option<DockerState> {
    if record.options.get("isolated")?.as_str()? != "docker" {
        return None;
    }
    let session_name = record.options.get("sessionName")?.as_str()?;
    inspect_docker_state(session_name)
}

/// Best-effort terminal exit code reported by the isolation backend itself
/// (currently docker via `docker inspect .State.ExitCode`). Returns None when
/// the backend cannot provide a real code, so callers never surface the `-1`
/// sentinel for a session whose real exit code is simply not available yet.
/// A running container has no terminal exit code (docker reports `0` for it),
/// so only a stopped container contributes one.
fn backend_exit_code(docker_state: Option<DockerState>) -> Option<i32> {
    let state = docker_state?;
    if state.running {
        None
    } else {
        state.exit_code
    }
}

/// Reconcile the OOM observation from the stored record and from `docker inspect`.
///
/// `State.OOMKilled` is a container-cgroup flag: the kernel sets it when ANY
/// process in the cgroup is OOM-killed and it is never cleared for the life of
/// the container (moby/moby#47618). It is therefore an *observation*, never a
/// verdict about the session (issue #151) — a container that lost one child
/// process keeps running and can still exit `0`. Once observed, the flag stays
/// `true` for the record.
fn resolve_oom_observation(
    record: &ExecutionRecord,
    docker_state: Option<DockerState>,
) -> Option<bool> {
    let inspected = docker_state.and_then(|state| state.oom_killed);
    if record.oom_killed == Some(true) || inspected == Some(true) {
        return Some(true);
    }
    if record.oom_killed == Some(false) || inspected == Some(false) {
        return Some(false);
    }
    None
}

/// Check if a detached isolation session is still running
/// Returns Some(true) if running, Some(false) if not, None if unable to determine
pub fn is_detached_session_alive(record: &ExecutionRecord) -> Option<bool> {
    let session_name = record.options.get("sessionName")?.as_str()?;
    let isolation_mode = record.options.get("isolationMode")?.as_str()?;
    let isolated = record.options.get("isolated")?.as_str()?;

    if isolation_mode != "detached" {
        return None;
    }

    match isolated {
        "screen" => {
            let output = Command::new("screen").args(["-ls"]).output().ok()?;
            let stdout = String::from_utf8_lossy(&output.stdout);
            Some(stdout.contains(session_name))
        }
        "tmux" => {
            let status = Command::new("tmux")
                .args(["has-session", "-t", session_name])
                .output()
                .ok()?;
            Some(status.status.success())
        }
        "docker" => {
            // A failed inspect means the container is not visible yet (still
            // being created on a slow DinD host) or already removed — not
            // "stopped". Return None (unknown) so the session is not falsely
            // marked finished (issue #136).
            inspect_docker_state(session_name).map(|state| state.running)
        }
        "ssh" => {
            // For SSH, check if the local wrapper PID is still running
            #[cfg(unix)]
            {
                if let Some(pid) = record.pid {
                    let result = unsafe { libc::kill(pid as i32, 0) };
                    Some(result == 0)
                } else {
                    None
                }
            }
            #[cfg(not(unix))]
            {
                let _ = record.pid;
                None
            }
        }
        _ => None,
    }
}

/// Number of trailing bytes scanned for the terminal log footer. The footer is
/// always appended at the very end of the log, so there is no reason to read
/// (potentially megabytes of) command output on every `--status` call.
const LOG_TAIL_BYTES: u64 = 16 * 1024;

/// Read the last `bytes` bytes of a file as (lossy) UTF-8 text.
///
/// A partial first line is dropped: the slice can start in the middle of a
/// line, and that fragment must not be treated as the beginning of a line by
/// the anchored footer matcher.
fn read_log_tail(log_path: &str, bytes: u64) -> Option<String> {
    let mut file = fs::File::open(log_path).ok()?;
    let size = file.metadata().ok()?.len();
    let length = size.min(bytes);
    file.seek(SeekFrom::Start(size - length)).ok()?;
    let mut buffer = Vec::with_capacity(length as usize);
    file.take(length).read_to_end(&mut buffer).ok()?;
    let tail = String::from_utf8_lossy(&buffer).into_owned();
    if size <= bytes {
        return Some(tail);
    }
    Some(match tail.find('\n') {
        Some(index) => tail[index + 1..].to_string(),
        None => String::new(),
    })
}

fn is_footer_separator_line(line: &str) -> bool {
    line.len() >= 10 && line.chars().all(|c| c == '=')
}

/// Read the terminal exit code from the anchored footer at the end of a log.
///
/// The footer `start` itself writes (see `create_log_footer()` and
/// `shell_log_footer_snippet()`) is a three-line block:
///
/// ```text
/// ==================================================
/// Finished: 2026-07-30 23:36:20.295
/// Exit Code: 0
/// ```
///
/// Matching the whole block at line starts means a bare `Exit Code: N`
/// substring emitted by the wrapped command (inside a JSON payload, a quoted
/// log excerpt, an `rg` dump, ...) can no longer be mistaken for the footer
/// (issue #150). Returns None when the log has no footer yet — never a number
/// parsed out of the command's own output.
pub fn read_exit_code_from_log(log_path: &str) -> Option<i32> {
    let tail = read_log_tail(log_path, LOG_TAIL_BYTES)?;
    let lines: Vec<&str> = tail
        .lines()
        .map(|line| line.trim_end_matches('\r'))
        .collect();
    for index in (2..lines.len()).rev() {
        let value = match lines[index].strip_prefix("Exit Code:") {
            Some(value) => value,
            None => continue,
        };
        if !lines[index - 1].starts_with("Finished:") || !is_footer_separator_line(lines[index - 2])
        {
            continue;
        }
        if let Ok(code) = value.trim().parse::<i32>() {
            return Some(code);
        }
    }
    None
}

/// Enrich execution record with live session status for detached executions.
/// If a record shows "executing" but the detached session has actually ended,
/// returns an updated copy with status "executed". If it shows "executed" but
/// the session is still running, returns a copy with status "executing".
pub fn enrich_detached_status(record: &ExecutionRecord) -> ExecutionRecord {
    let footer_exit = read_exit_code_from_log(&record.log_path);
    let is_detached_docker = is_detached_docker_record(record);
    let docker_state = if is_detached_docker {
        read_docker_state(record)
    } else {
        None
    };

    // `oomKilled` is exposed alongside the status, but never decides it (#151).
    let oom_killed = resolve_oom_observation(record, docker_state);
    let clone_record = || {
        let mut enriched = record.clone();
        if oom_killed.is_some() {
            enriched.oom_killed = oom_killed;
        }
        enriched
    };

    let alive = if is_detached_docker {
        docker_state.map(|state| state.running)
    } else {
        is_detached_session_alive(record)
    };

    let alive = match alive {
        Some(value) => value,
        None => {
            // Liveness is unknown: the backend could not be probed (e.g. a
            // detached docker container that is not visible yet on a slow
            // Docker-in-Docker host, or one that has already been removed).
            // Honor a terminal `Exit Code:` footer if the command wrote one;
            // otherwise leave the record untouched (still executing) rather than
            // fabricating a `-1` terminal result that orchestrators misread as a
            // finished/failed run (issue #136).
            let is_detached =
                record.options.get("isolationMode").and_then(|v| v.as_str()) == Some("detached");
            if is_detached && record.status == ExecutionStatus::Executing {
                if footer_exit.is_some() {
                    let mut enriched = clone_record();
                    enriched.status = ExecutionStatus::Executed;
                    enriched.exit_code = footer_exit;
                    if enriched.end_time.is_none() {
                        enriched.end_time = Some(chrono::Utc::now().to_rfc3339());
                    }
                    return enriched;
                }
                if oom_killed == Some(true) {
                    // The container is gone and wrote no footer, so the OOM
                    // observation is the only evidence left: report the session
                    // as finished with the conventional SIGKILL code (issue
                    // #148). While the container is still inspectable this
                    // branch is never taken — a live container keeps the session
                    // `executing` no matter what the cgroup flag says (#151).
                    let mut enriched = clone_record();
                    enriched.status = ExecutionStatus::Executed;
                    enriched.exit_code = Some(137);
                    if enriched.end_time.is_none() {
                        enriched.end_time = Some(chrono::Utc::now().to_rfc3339());
                    }
                    return enriched;
                }
            }
            return clone_record();
        }
    };

    let mut enriched = clone_record();

    if alive && enriched.status == ExecutionStatus::Executed {
        // A live `screen -ls` (or `tmux`/`docker`) session does NOT mean the command
        // is still running: a lingering shell can outlive a killed command (e.g. the
        // OOM killer sends SIGKILL, exit 137, but the login shell stays up for a
        // window after `start` already wrote the terminal footer). The footer/recorded
        // exit code is authoritative. Only flip back to "executing" when there is NO
        // recorded terminal exit code AND no `Exit Code:` footer in the log.
        if enriched.exit_code.is_none() && footer_exit.is_none() {
            // Session still running and no terminal record - correct it
            enriched.status = ExecutionStatus::Executing;
            enriched.exit_code = None;
            enriched.end_time = None;
        }
        // Otherwise keep the recorded/footer exit code - the command has finished.
    } else if !alive && enriched.status == ExecutionStatus::Executing {
        // Session ended but record says executing - correct it. Resolve a real
        // exit code: prefer the backend's own record (e.g. `docker inspect
        // .State.ExitCode`, which is authoritative and cannot be spoofed by
        // command output — issue #150), then the anchored log footer, then
        // `137` when the only evidence left is the OOM observation, and only
        // fall back to the `-1` sentinel as a last resort when no real code can
        // be obtained (issues #136, #151).
        enriched.status = ExecutionStatus::Executed;
        if enriched.exit_code.is_none() {
            enriched.exit_code = Some(
                backend_exit_code(docker_state)
                    .or(footer_exit)
                    .or(if oom_killed == Some(true) {
                        Some(137)
                    } else {
                        None
                    })
                    .unwrap_or(-1),
            );
        }
        if enriched.end_time.is_none() {
            enriched.end_time = Some(chrono::Utc::now().to_rfc3339());
        }
    }

    enriched
}

/// Compute a `currentTime` value for a record if its status is `executing`.
/// Returns `None` for completed records. Wrapping this in a helper makes it
/// easy to attach the same timestamp to all output formats and to test the
/// behavior deterministically.
pub fn attach_current_time(record: &ExecutionRecord) -> Option<String> {
    if record.status == ExecutionStatus::Executing {
        Some(chrono::Utc::now().to_rfc3339())
    } else {
        None
    }
}

/// Format execution record as Links Notation (indented style)
/// Uses nested Links notation for object values (like options) instead of JSON
///
/// Output format:
/// ```text
/// <uuid>
///   <key> <value>
///   options
///     <nested_key> <nested_value>
///   ...
/// ```
pub fn format_record_as_links_notation(record: &ExecutionRecord) -> String {
    format_record_as_links_notation_with_current_time(record, None)
}

/// Same as [`format_record_as_links_notation`] but injects a `currentTime`
/// field (right after `startTime`) when a value is supplied.
pub fn format_record_as_links_notation_with_current_time(
    record: &ExecutionRecord,
    current_time: Option<&str>,
) -> String {
    format_record_as_links_notation_with_enrichments(record, current_time, None)
}

fn append_links_array(lines: &mut Vec<String>, values: &[Value], indent: usize) {
    let prefix = " ".repeat(indent);
    if values.is_empty() {
        lines.push(format!("{}()", prefix));
        return;
    }

    lines.push(format!("{}(", prefix));
    for value in values {
        match value {
            Value::Array(nested) => append_links_array(lines, nested, indent + 2),
            Value::Object(map) => {
                for (child_key, child_value) in map {
                    if !child_value.is_null() {
                        append_links_value(lines, child_key, child_value, indent + 2);
                    }
                }
            }
            _ => lines.push(format!(
                "{}{}",
                " ".repeat(indent + 2),
                format_value_for_links_notation(value)
            )),
        }
    }
    lines.push(format!("{})", prefix));
}

fn append_links_value(lines: &mut Vec<String>, key: &str, value: &Value, indent: usize) {
    let prefix = " ".repeat(indent);
    match value {
        Value::Object(map) => {
            if map.is_empty() {
                return;
            }
            lines.push(format!("{}{}", prefix, key));
            for (child_key, child_value) in map {
                if !child_value.is_null() {
                    append_links_value(lines, child_key, child_value, indent + 4);
                }
            }
        }
        Value::Array(values) => {
            lines.push(format!("{}{}", prefix, key));
            append_links_array(lines, values, indent + 2);
        }
        _ => lines.push(format!(
            "{}{} {}",
            prefix,
            key,
            format_value_for_links_notation(value)
        )),
    }
}

fn format_record_as_links_notation_with_enrichments(
    record: &ExecutionRecord,
    current_time: Option<&str>,
    process_ids: Option<&Value>,
) -> String {
    let json = record.to_json();
    let mut lines = vec![record.uuid.clone()];

    if let Value::Object(map) = json {
        for (key, value) in map {
            if !value.is_null() {
                if key == "options" {
                    // Format options as nested Links notation
                    if let Value::Object(opts) = &value {
                        if !opts.is_empty() {
                            lines.push("  options".to_string());
                            for (opt_key, opt_value) in opts {
                                if !opt_value.is_null() {
                                    let formatted = format_value_for_links_notation(opt_value);
                                    lines.push(format!("    {} {}", opt_key, formatted));
                                }
                            }
                        }
                    }
                } else {
                    let formatted_value = match &value {
                        Value::String(s) => escape_for_links_notation(s),
                        Value::Bool(b) => b.to_string(),
                        Value::Number(n) => n.to_string(),
                        Value::Null => "null".to_string(),
                        Value::Object(_) | Value::Array(_) => {
                            // For other complex types, use nested format
                            format_value_for_links_notation(&value)
                        }
                    };
                    lines.push(format!("  {} {}", key, formatted_value));
                }
            }

            // Insert processIds right after pid so status output groups process
            // identity with the wrapper PID already present in older output.
            if key == "pid" {
                if let Some(process_ids) = process_ids {
                    append_links_value(&mut lines, "processIds", process_ids, 2);
                }
            }

            // Insert currentTime right after startTime for readability
            if key == "startTime" {
                if let Some(ct) = current_time {
                    lines.push(format!("  currentTime {}", escape_for_links_notation(ct)));
                }
            }
        }
    }

    lines.join("\n")
}

/// Format execution record as human-readable text
pub fn format_record_as_text(record: &ExecutionRecord) -> String {
    format_record_as_text_with_current_time(record, None)
}

/// Same as [`format_record_as_text`] but adds a `Current Time:` line right
/// after `Start Time:` when a value is supplied.
pub fn format_record_as_text_with_current_time(
    record: &ExecutionRecord,
    current_time: Option<&str>,
) -> String {
    format_record_as_text_with_enrichments(record, current_time, None)
}

fn append_text_process_ids(lines: &mut Vec<String>, process_ids: &Value) {
    let Value::Object(map) = process_ids else {
        return;
    };
    if map.is_empty() {
        return;
    }

    lines.push("Process IDs:".to_string());
    for (key, value) in map {
        let value_str = match value {
            Value::String(s) => s.clone(),
            Value::Bool(b) => b.to_string(),
            Value::Number(n) => n.to_string(),
            Value::Null => "null".to_string(),
            other => serde_json::to_string(other).unwrap_or_default(),
        };
        lines.push(format!("  {}: {}", key, value_str));
    }
}

fn format_record_as_text_with_enrichments(
    record: &ExecutionRecord,
    current_time: Option<&str>,
    process_ids: Option<&Value>,
) -> String {
    let exit_code_str = record
        .exit_code
        .map(|c| c.to_string())
        .unwrap_or_else(|| "N/A".to_string());
    let pid_str = record
        .pid
        .map(|p| p.to_string())
        .unwrap_or_else(|| "N/A".to_string());
    let end_time_str = record.end_time.as_deref().unwrap_or("N/A");

    let mut lines = vec![
        "Execution Status".to_string(),
        "=".repeat(50),
        format!("UUID:              {}", record.uuid),
        format!("Status:            {}", record.status),
        format!("Command:           {}", record.command),
        format!("Exit Code:         {}", exit_code_str),
    ];
    if let Some(oom_killed) = record.oom_killed {
        lines.push(format!("OOM Killed:        {}", oom_killed));
    }
    lines.push(format!("PID:               {}", pid_str));
    if let Some(process_ids) = process_ids {
        append_text_process_ids(&mut lines, process_ids);
    }
    lines.extend([
        format!("Working Directory: {}", record.working_directory),
        format!("Shell:             {}", record.shell),
        format!("Platform:          {}", record.platform),
        format!("Start Time:        {}", record.start_time),
    ]);
    if let Some(ct) = current_time {
        lines.push(format!("Current Time:      {}", ct));
    }
    lines.push(format!("End Time:          {}", end_time_str));
    lines.push(format!("Log Path:          {}", record.log_path));

    // Format options as nested list instead of JSON
    if !record.options.is_empty() {
        lines.push("Options:".to_string());
        for (key, value) in &record.options {
            let value_str = match value {
                Value::String(s) => s.clone(),
                Value::Bool(b) => b.to_string(),
                Value::Number(n) => n.to_string(),
                Value::Null => "null".to_string(),
                other => serde_json::to_string(other).unwrap_or_default(),
            };
            lines.push(format!("  {}: {}", key, value_str));
        }
    }

    lines.join("\n")
}

fn record_json_with_enrichments(
    record: &ExecutionRecord,
    current_time: Option<&str>,
    process_ids: Option<&Value>,
) -> Value {
    let mut json = record.to_json();
    if let Value::Object(map) = &mut json {
        if let Some(process_ids) = process_ids {
            map.insert("processIds".to_string(), process_ids.clone());
        }
        if let Some(ct) = current_time {
            map.insert("currentTime".to_string(), Value::String(ct.to_string()));
        }
    }
    json
}

/// Format execution record based on format type
pub fn format_record(record: &ExecutionRecord, format: &str) -> Result<String, String> {
    format_record_with_current_time(record, format, None)
}

/// Same as [`format_record`] but the output includes `currentTime` when a
/// value is supplied. Use this from [`query_status`] so all three formats
/// stay in sync.
pub fn format_record_with_current_time(
    record: &ExecutionRecord,
    format: &str,
    current_time: Option<&str>,
) -> Result<String, String> {
    format_record_with_enrichments(record, format, current_time, None)
}

fn format_record_with_enrichments(
    record: &ExecutionRecord,
    format: &str,
    current_time: Option<&str>,
    process_ids: Option<&Value>,
) -> Result<String, String> {
    match format {
        "links-notation" => Ok(format_record_as_links_notation_with_enrichments(
            record,
            current_time,
            process_ids,
        )),
        "json" => serde_json::to_string_pretty(&record_json_with_enrichments(
            record,
            current_time,
            process_ids,
        ))
        .map_err(|e| format!("Failed to serialize to JSON: {}", e)),
        "text" => Ok(format_record_as_text_with_enrichments(
            record,
            current_time,
            process_ids,
        )),
        _ => Err(format!("Unknown output format: {}", format)),
    }
}

fn sort_records_by_start_time_desc(records: &mut [ExecutionRecord]) {
    records.sort_by(|a, b| b.start_time.cmp(&a.start_time));
}

fn indent_block(block: &str, spaces: usize) -> String {
    let prefix = " ".repeat(spaces);
    block
        .lines()
        .map(|line| format!("{}{}", prefix, line))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Format execution records as a Links Notation list.
pub fn format_record_list_as_links_notation(records: &[ExecutionRecord]) -> String {
    let current_times: Vec<Option<String>> = records.iter().map(attach_current_time).collect();
    let process_ids = vec![None; records.len()];
    format_record_list_as_links_notation_with_current_times(records, &current_times, &process_ids)
}

fn format_record_list_as_links_notation_with_current_times(
    records: &[ExecutionRecord],
    current_times: &[Option<String>],
    process_ids: &[Option<Value>],
) -> String {
    let mut lines = vec![
        "executions".to_string(),
        format!("  count {}", records.len()),
    ];

    if records.is_empty() {
        lines.push("  records ()".to_string());
        return lines.join("\n");
    }

    lines.push("  records".to_string());
    for ((record, current_time), process_ids) in records
        .iter()
        .zip(current_times.iter())
        .zip(process_ids.iter())
    {
        let block = format_record_as_links_notation_with_enrichments(
            record,
            current_time.as_deref(),
            process_ids.as_ref(),
        );
        lines.push(indent_block(&block, 4));
    }

    lines.join("\n")
}

/// Format execution records as human-readable text.
pub fn format_record_list_as_text(records: &[ExecutionRecord]) -> String {
    let current_times: Vec<Option<String>> = records.iter().map(attach_current_time).collect();
    let process_ids = vec![None; records.len()];
    format_record_list_as_text_with_current_times(records, &current_times, &process_ids)
}

fn format_record_list_as_text_with_current_times(
    records: &[ExecutionRecord],
    current_times: &[Option<String>],
    process_ids: &[Option<Value>],
) -> String {
    let mut lines = vec![
        "Executions".to_string(),
        "=".repeat(50),
        format!("Count: {}", records.len()),
    ];

    for ((record, current_time), process_ids) in records
        .iter()
        .zip(current_times.iter())
        .zip(process_ids.iter())
    {
        lines.push(String::new());
        lines.push(format_record_as_text_with_enrichments(
            record,
            current_time.as_deref(),
            process_ids.as_ref(),
        ));
    }

    lines.join("\n")
}

fn record_list_json_with_current_times(
    records: &[ExecutionRecord],
    current_times: &[Option<String>],
    process_ids: &[Option<Value>],
) -> Value {
    let executions: Vec<Value> = records
        .iter()
        .zip(current_times.iter())
        .zip(process_ids.iter())
        .map(|((record, current_time), process_ids)| {
            record_json_with_enrichments(record, current_time.as_deref(), process_ids.as_ref())
        })
        .collect();

    serde_json::json!({
        "count": records.len(),
        "executions": executions,
    })
}

/// Format execution records based on format type.
pub fn format_record_list(records: &[ExecutionRecord], format: &str) -> Result<String, String> {
    let current_times: Vec<Option<String>> = records.iter().map(attach_current_time).collect();
    let process_ids = vec![None; records.len()];
    format_record_list_with_current_times(records, format, &current_times, &process_ids)
}

fn format_record_list_with_current_times(
    records: &[ExecutionRecord],
    format: &str,
    current_times: &[Option<String>],
    process_ids: &[Option<Value>],
) -> Result<String, String> {
    match format {
        "links-notation" => Ok(format_record_list_as_links_notation_with_current_times(
            records,
            current_times,
            process_ids,
        )),
        "json" => serde_json::to_string_pretty(&record_list_json_with_current_times(
            records,
            current_times,
            process_ids,
        ))
        .map_err(|e| format!("Failed to serialize to JSON: {}", e)),
        "text" => Ok(format_record_list_as_text_with_current_times(
            records,
            current_times,
            process_ids,
        )),
        _ => Err(format!("Unknown output format: {}", format)),
    }
}

/// Query result from status lookup
pub struct StatusQueryResult {
    pub success: bool,
    pub output: Option<String>,
    pub error: Option<String>,
}

/// Handle execution list query and return the result
pub fn list_executions(
    store: Option<&ExecutionStore>,
    output_format: Option<&str>,
) -> StatusQueryResult {
    let store = match store {
        Some(s) => s,
        None => {
            return StatusQueryResult {
                success: false,
                output: None,
                error: Some("Execution tracking is disabled.".to_string()),
            }
        }
    };

    let mut records: Vec<ExecutionRecord> =
        store.get_all().iter().map(enrich_detached_status).collect();
    sort_records_by_start_time_desc(&mut records);
    let current_times: Vec<Option<String>> = records.iter().map(attach_current_time).collect();
    let process_ids: Vec<Option<Value>> = records.iter().map(collect_process_ids).collect();
    let format = output_format.unwrap_or("links-notation");

    match format_record_list_with_current_times(&records, format, &current_times, &process_ids) {
        Ok(output) => StatusQueryResult {
            success: true,
            output: Some(output),
            error: None,
        },
        Err(e) => StatusQueryResult {
            success: false,
            output: None,
            error: Some(e),
        },
    }
}

/// Handle status query and return the result
pub fn query_status(
    store: Option<&ExecutionStore>,
    identifier: &str,
    output_format: Option<&str>,
) -> StatusQueryResult {
    let store = match store {
        Some(s) => s,
        None => {
            return StatusQueryResult {
                success: false,
                output: None,
                error: Some("Execution tracking is disabled.".to_string()),
            }
        }
    };

    let record = match store.get(identifier) {
        Some(r) => r,
        None => {
            return StatusQueryResult {
                success: false,
                output: None,
                error: Some(format!(
                    "No execution found with UUID or session name: {}",
                    identifier
                )),
            }
        }
    };

    // Enrich detached execution status with live session check
    let enriched = enrich_detached_status(&record);
    // Attach currentTime so callers can see how long an executing command has been running
    let current_time = attach_current_time(&enriched);
    let process_ids = collect_process_ids(&enriched);

    let format = output_format.unwrap_or("links-notation");
    match format_record_with_enrichments(
        &enriched,
        format,
        current_time.as_deref(),
        process_ids.as_ref(),
    ) {
        Ok(output) => StatusQueryResult {
            success: true,
            output: Some(output),
            error: None,
        },
        Err(e) => StatusQueryResult {
            success: false,
            output: None,
            error: Some(e),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::execution_store::ExecutionRecordOptions;
    use serde_json::json;

    fn executing_record() -> ExecutionRecord {
        ExecutionRecord::with_options(ExecutionRecordOptions {
            command: "sleep 60".to_string(),
            uuid: Some("issue-126-rust".to_string()),
            pid: Some(667105),
            status: Some(ExecutionStatus::Executing),
            log_path: Some("/tmp/issue-126.log".to_string()),
            start_time: Some("2026-04-23T10:00:00Z".to_string()),
            working_directory: Some("/home/user".to_string()),
            shell: Some("/bin/bash".to_string()),
            platform: Some("linux".to_string()),
            ..Default::default()
        })
    }

    #[test]
    fn links_notation_indents_nested_process_id_arrays() {
        let process_ids = json!({
            "wrapperPid": 667105,
            "screenPid": 667120,
            "commandPids": [667121, 667122],
        });
        let output = format_record_with_enrichments(
            &executing_record(),
            "links-notation",
            Some("2026-04-23T10:10:13.042Z"),
            Some(&process_ids),
        )
        .expect("links-notation should format");

        assert!(
            output.contains(
                "      commandPids\n        (\n          667121\n          667122\n        )"
            ),
            "processIds should be a nested indented block, output: {}",
            output
        );
        assert!(
            !output.contains("\n(\n"),
            "opening parenthesis must not start at column 1: {}",
            output
        );
    }
}