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
//! 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::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::process::Command;

/// 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" => {
            let output = Command::new("docker")
                .args(["inspect", "-f", "{{.State.Running}}", session_name])
                .output()
                .ok()?;
            let stdout = String::from_utf8_lossy(&output.stdout);
            Some(stdout.trim() == "true")
        }
        "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,
    }
}

fn read_exit_code_from_log(log_path: &str) -> Option<i32> {
    let content = fs::read_to_string(log_path).ok()?;
    content
        .lines()
        .rev()
        .find_map(|line| line.trim().strip_prefix("Exit Code:"))
        .and_then(|value| value.trim().parse::<i32>().ok())
}

/// 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 alive = match is_detached_session_alive(record) {
        Some(v) => v,
        None => return record.clone(),
    };

    let mut enriched = record.clone();

    if alive && enriched.status == ExecutionStatus::Executed {
        // Session still running but record says executed - correct it
        enriched.status = ExecutionStatus::Executing;
        enriched.exit_code = None;
        enriched.end_time = None;
    } else if !alive && enriched.status == ExecutionStatus::Executing {
        // Session ended but record says executing - correct it
        enriched.status = ExecutionStatus::Executed;
        if enriched.exit_code.is_none() {
            enriched.exit_code = Some(read_exit_code_from_log(&enriched.log_path).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),
        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
        );
    }
}