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
//! Tests for --status lookup by session name and detached status enrichment
//! Issue #101: --session name not usable with --status, and --detached reports immediate completion
//! Issue #105: currentTime added to --status output for executing commands

use start_command::{
    attach_current_time, enrich_detached_status, is_detached_session_alive, query_status,
    ExecutionRecord, ExecutionRecordOptions, ExecutionStatus, ExecutionStore,
    ExecutionStoreOptions,
};
use std::collections::HashMap;
use tempfile::TempDir;

/// Helper to create a test store in a temporary directory
fn create_test_store() -> (TempDir, ExecutionStore) {
    let temp_dir = TempDir::new().unwrap();
    let store = ExecutionStore::with_options(ExecutionStoreOptions {
        app_folder: Some(temp_dir.path().to_path_buf()),
        use_links: Some(false),
        verbose: false,
    });
    (temp_dir, store)
}

/// Helper to create isolation options with session name
fn make_isolation_options(
    session_name: &str,
    isolated: &str,
    isolation_mode: &str,
) -> HashMap<String, serde_json::Value> {
    let mut opts = HashMap::new();
    opts.insert(
        "sessionName".to_string(),
        serde_json::Value::String(session_name.to_string()),
    );
    opts.insert(
        "isolated".to_string(),
        serde_json::Value::String(isolated.to_string()),
    );
    opts.insert(
        "isolationMode".to_string(),
        serde_json::Value::String(isolation_mode.to_string()),
    );
    opts
}

// ===== ExecutionStore::get() session name lookup tests =====

#[test]
fn test_get_by_uuid() {
    let (_temp_dir, store) = create_test_store();

    let mut record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "echo hello".to_string(),
        uuid: Some("test-uuid-session-101".to_string()),
        pid: Some(12345),
        options: Some(make_isolation_options("my-session", "screen", "attached")),
        ..Default::default()
    });
    record.complete(0);
    store.save(&record).unwrap();

    let found = store.get("test-uuid-session-101");
    assert!(found.is_some());
    assert_eq!(found.unwrap().uuid, "test-uuid-session-101");
}

#[test]
fn test_get_by_session_name() {
    let (_temp_dir, store) = create_test_store();

    let record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "sleep 60".to_string(),
        uuid: Some("uuid-for-session-lookup-test".to_string()),
        pid: Some(12345),
        options: Some(make_isolation_options(
            "my-custom-session",
            "screen",
            "detached",
        )),
        ..Default::default()
    });
    store.save(&record).unwrap();

    let found = store.get("my-custom-session");
    assert!(found.is_some());
    let found = found.unwrap();
    assert_eq!(found.uuid, "uuid-for-session-lookup-test");
    assert_eq!(
        found.options.get("sessionName").unwrap().as_str().unwrap(),
        "my-custom-session"
    );
}

#[test]
fn test_get_prefers_uuid_over_session_name() {
    let (_temp_dir, store) = create_test_store();

    // Record 1 with a specific UUID
    let mut record1 = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "echo first".to_string(),
        uuid: Some("target-uuid-101".to_string()),
        pid: Some(111),
        options: Some(make_isolation_options("some-session", "screen", "attached")),
        ..Default::default()
    });
    record1.complete(0);
    store.save(&record1).unwrap();

    // Record 2 whose session name matches record1's UUID
    let record2 = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "echo second".to_string(),
        uuid: Some("other-uuid-101".to_string()),
        pid: Some(222),
        options: Some(make_isolation_options(
            "target-uuid-101",
            "screen",
            "detached",
        )),
        ..Default::default()
    });
    store.save(&record2).unwrap();

    // Looking up by record1's UUID should return record1, not record2
    let found = store.get("target-uuid-101").unwrap();
    assert_eq!(found.command, "echo first");
}

#[test]
fn test_get_nonexistent_session_name() {
    let (_temp_dir, store) = create_test_store();

    let found = store.get("nonexistent-session");
    assert!(found.is_none());
}

#[test]
fn test_get_record_without_session_name() {
    let (_temp_dir, store) = create_test_store();

    let record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "echo hello".to_string(),
        uuid: Some("no-session-name-uuid".to_string()),
        pid: Some(12345),
        ..Default::default()
    });
    store.save(&record).unwrap();

    let found = store.get("some-session-name");
    assert!(found.is_none());
}

// ===== query_status() with session name tests =====

#[test]
fn test_query_status_by_session_name() {
    let (_temp_dir, store) = create_test_store();

    let mut record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "sleep 60".to_string(),
        uuid: Some("query-session-uuid-101".to_string()),
        pid: Some(12345),
        options: Some(make_isolation_options(
            "my-query-session",
            "screen",
            "attached",
        )),
        ..Default::default()
    });
    record.complete(0);
    store.save(&record).unwrap();

    let result = query_status(Some(&store), "my-query-session", Some("json"));
    assert!(result.success);
    let output = result.output.unwrap();
    assert!(output.contains("query-session-uuid-101"));
    assert!(output.contains("sleep 60"));
}

#[test]
fn test_query_status_nonexistent_session_name() {
    let (_temp_dir, store) = create_test_store();

    let result = query_status(Some(&store), "nonexistent-session", Some("json"));
    assert!(!result.success);
    assert!(result
        .error
        .unwrap()
        .contains("No execution found with UUID or session name"));
}

// ===== Detached status enrichment tests =====

#[test]
fn test_is_detached_session_alive_non_detached() {
    let record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "echo hello".to_string(),
        options: Some(make_isolation_options("test", "screen", "attached")),
        ..Default::default()
    });
    assert!(is_detached_session_alive(&record).is_none());
}

#[test]
fn test_is_detached_session_alive_no_session_name() {
    let record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "echo hello".to_string(),
        ..Default::default()
    });
    assert!(is_detached_session_alive(&record).is_none());
}

#[test]
fn test_is_detached_session_alive_nonexistent_screen() {
    let record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "sleep 60".to_string(),
        options: Some(make_isolation_options(
            "nonexistent-screen-session-test-101",
            "screen",
            "detached",
        )),
        ..Default::default()
    });
    let alive = is_detached_session_alive(&record);
    // May be Some(false) or None depending on whether screen is installed
    if let Some(v) = alive {
        assert!(!v);
    }
}

#[test]
fn test_enrich_detached_status_non_detached() {
    let mut record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "echo hello".to_string(),
        options: Some(make_isolation_options("test", "screen", "attached")),
        ..Default::default()
    });
    record.complete(0);

    let enriched = enrich_detached_status(&record);
    assert_eq!(enriched.status, ExecutionStatus::Executed);
    assert_eq!(enriched.exit_code, Some(0));
}

#[test]
fn test_enrich_detached_status_marks_dead_session_as_executed() {
    let record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "sleep 60".to_string(),
        options: Some(make_isolation_options(
            "nonexistent-session-enrich-101",
            "screen",
            "detached",
        )),
        ..Default::default()
    });
    // Record says executing, but session doesn't exist

    let enriched = enrich_detached_status(&record);
    // If screen is available, should mark as executed with exit code -1
    if enriched.status == ExecutionStatus::Executed {
        assert_eq!(enriched.exit_code, Some(-1));
        assert!(enriched.end_time.is_some());
    }
}

#[test]
fn test_get_most_recent_session_name_match() {
    let (_temp_dir, store) = create_test_store();

    // Create two records with the same session name (e.g., reuse of session name)
    let mut record1 = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "echo first".to_string(),
        uuid: Some("older-uuid-101".to_string()),
        pid: Some(111),
        options: Some(make_isolation_options(
            "reused-session",
            "screen",
            "attached",
        )),
        ..Default::default()
    });
    record1.complete(0);
    store.save(&record1).unwrap();

    let record2 = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "echo second".to_string(),
        uuid: Some("newer-uuid-101".to_string()),
        pid: Some(222),
        options: Some(make_isolation_options(
            "reused-session",
            "screen",
            "detached",
        )),
        ..Default::default()
    });
    store.save(&record2).unwrap();

    // Should find the first matching record (order depends on storage)
    let found = store.get("reused-session");
    assert!(found.is_some());
    // Both records have this session name; get() returns the first match
    let found = found.unwrap();
    assert!(found.uuid == "older-uuid-101" || found.uuid == "newer-uuid-101");
}

// ===== Issue #105: attach_current_time for executing status =====

#[test]
fn test_attach_current_time_returns_some_for_executing_record() {
    let record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "sleep 60".to_string(),
        uuid: Some("issue-105-executing".to_string()),
        pid: Some(12345),
        status: Some(ExecutionStatus::Executing),
        log_path: Some("/tmp/test.log".to_string()),
        ..Default::default()
    });

    let before = chrono::Utc::now();
    let current_time = attach_current_time(&record);
    let after = chrono::Utc::now();

    assert!(current_time.is_some());
    let ct = current_time.unwrap();
    let parsed = chrono::DateTime::parse_from_rfc3339(&ct)
        .expect("currentTime must be a valid RFC3339 timestamp");
    assert!(parsed >= before - chrono::Duration::milliseconds(1));
    assert!(parsed <= after + chrono::Duration::milliseconds(1));
}

#[test]
fn test_attach_current_time_returns_none_for_executed_record() {
    let mut record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "echo hello".to_string(),
        uuid: Some("issue-105-executed".to_string()),
        pid: Some(12345),
        log_path: Some("/tmp/test.log".to_string()),
        ..Default::default()
    });
    record.complete(0);

    assert_eq!(record.status, ExecutionStatus::Executed);
    assert!(attach_current_time(&record).is_none());
}

#[test]
fn test_attach_current_time_does_not_mutate_record() {
    let record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "sleep 60".to_string(),
        uuid: Some("issue-105-no-mutation".to_string()),
        pid: Some(12345),
        status: Some(ExecutionStatus::Executing),
        log_path: Some("/tmp/test.log".to_string()),
        ..Default::default()
    });
    let snapshot = record.clone();
    let _ = attach_current_time(&record);
    assert_eq!(record.uuid, snapshot.uuid);
    assert_eq!(record.status, snapshot.status);
    assert_eq!(record.start_time, snapshot.start_time);
    assert_eq!(record.end_time, snapshot.end_time);
    assert_eq!(record.exit_code, snapshot.exit_code);
}

// ===== Issue #105: query_status surfaces currentTime via all formats =====

#[test]
fn test_query_status_json_includes_current_time_for_executing() {
    let (_temp_dir, store) = create_test_store();
    let before = chrono::Utc::now();

    let record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "sleep 100".to_string(),
        uuid: Some("issue-105-json-executing".to_string()),
        pid: Some(99999),
        status: Some(ExecutionStatus::Executing),
        log_path: Some("/tmp/executing.log".to_string()),
        ..Default::default()
    });
    store.save(&record).unwrap();

    let result = query_status(Some(&store), "issue-105-json-executing", Some("json"));
    assert!(result.success);
    let output = result.output.unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&output).unwrap();

    let ct = parsed["currentTime"]
        .as_str()
        .expect("currentTime should be present and a string");
    let parsed_ct = chrono::DateTime::parse_from_rfc3339(ct)
        .expect("currentTime must be a valid RFC3339 timestamp");
    let after = chrono::Utc::now();
    assert!(parsed_ct >= before - chrono::Duration::seconds(1));
    assert!(parsed_ct <= after + chrono::Duration::seconds(1));
}

#[test]
fn test_query_status_json_omits_current_time_for_executed() {
    let (_temp_dir, store) = create_test_store();

    let mut record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "echo done".to_string(),
        uuid: Some("issue-105-json-executed".to_string()),
        pid: Some(11111),
        log_path: Some("/tmp/done.log".to_string()),
        ..Default::default()
    });
    record.complete(0);
    store.save(&record).unwrap();

    let result = query_status(Some(&store), "issue-105-json-executed", Some("json"));
    assert!(result.success);
    let output = result.output.unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&output).unwrap();

    assert_eq!(parsed["status"], "executed");
    assert!(
        parsed.get("currentTime").is_none() || parsed["currentTime"].is_null(),
        "currentTime must not be present on completed records, got: {}",
        output
    );
}

#[test]
fn test_query_status_links_notation_includes_current_time_for_executing() {
    let (_temp_dir, store) = create_test_store();

    let record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "sleep 100".to_string(),
        uuid: Some("issue-105-links-executing".to_string()),
        pid: Some(99999),
        status: Some(ExecutionStatus::Executing),
        log_path: Some("/tmp/executing.log".to_string()),
        ..Default::default()
    });
    store.save(&record).unwrap();

    let result = query_status(Some(&store), "issue-105-links-executing", None);
    assert!(result.success);
    let output = result.output.unwrap();

    assert!(output.contains("status executing"));
    // currentTime should appear as an indented property with an ISO-like timestamp value
    let re = regex::Regex::new(r"\n  currentTime .*\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}").unwrap();
    assert!(
        re.is_match(&output),
        "currentTime missing or unrecognized in links-notation output: {}",
        output
    );
}

#[test]
fn test_query_status_text_includes_current_time_for_executing() {
    let (_temp_dir, store) = create_test_store();

    let record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "sleep 100".to_string(),
        uuid: Some("issue-105-text-executing".to_string()),
        pid: Some(99999),
        status: Some(ExecutionStatus::Executing),
        log_path: Some("/tmp/executing.log".to_string()),
        ..Default::default()
    });
    store.save(&record).unwrap();

    let result = query_status(Some(&store), "issue-105-text-executing", Some("text"));
    assert!(result.success);
    let output = result.output.unwrap();

    assert!(output.contains("Status:"));
    assert!(output.contains("executing"));
    assert!(output.contains("Current Time:"));
    // Current Time should appear right after Start Time
    let start_idx = output.find("Start Time:").expect("Start Time line");
    let current_idx = output.find("Current Time:").expect("Current Time line");
    assert!(current_idx > start_idx);
}

#[test]
fn test_query_status_text_omits_current_time_for_executed() {
    let (_temp_dir, store) = create_test_store();

    let mut record = ExecutionRecord::with_options(ExecutionRecordOptions {
        command: "echo done".to_string(),
        uuid: Some("issue-105-text-executed".to_string()),
        pid: Some(11111),
        log_path: Some("/tmp/done.log".to_string()),
        ..Default::default()
    });
    record.complete(0);
    store.save(&record).unwrap();

    let result = query_status(Some(&store), "issue-105-text-executed", Some("text"));
    assert!(result.success);
    let output = result.output.unwrap();

    assert!(!output.contains("Current Time:"));
}