sendword 0.9.0

Simple HTTP webhook to command runner sidecar. Frontend for managing hooks, JSON state for config portability, SQLite for execution history and logs.
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
pub mod http;
pub mod script;
pub mod shell;

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

use sqlx::SqlitePool;
use tokio::fs;

use crate::config::{ExecutorConfig, HttpMethod};
use crate::interpolation::interpolate_command;
use crate::models::ExecutionStatus;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ScriptRuntime {
    Direct,
    JavaScript,
    Python,
}

/// Which executor to use for a hook.
#[derive(Clone)]
pub enum ResolvedExecutor {
    Shell {
        command: String,
    },
    Script {
        path: PathBuf,
        runtime: ScriptRuntime,
    },
    Http {
        method: HttpMethod,
        url: String,
        headers: HashMap<String, String>,
        body: Option<String>,
        follow_redirects: bool,
    },
}

pub fn resolve_executor(config: &ExecutorConfig, payload_json: &str) -> ResolvedExecutor {
    match config {
        ExecutorConfig::Shell { command } => {
            let interpolated = if let Ok(payload_value) =
                serde_json::from_str::<serde_json::Value>(payload_json)
            {
                interpolate_command(command, &payload_value).into_owned()
            } else {
                command.clone()
            };
            ResolvedExecutor::Shell {
                command: interpolated,
            }
        }
        ExecutorConfig::Script { path } => ResolvedExecutor::Script {
            path: PathBuf::from(path),
            runtime: ScriptRuntime::Direct,
        },
        ExecutorConfig::JavaScript { path } => ResolvedExecutor::Script {
            path: PathBuf::from(path),
            runtime: ScriptRuntime::JavaScript,
        },
        ExecutorConfig::Python { path } => ResolvedExecutor::Script {
            path: PathBuf::from(path),
            runtime: ScriptRuntime::Python,
        },
        ExecutorConfig::Http {
            method,
            url,
            headers,
            body,
            follow_redirects,
        } => {
            let payload_value: serde_json::Value = serde_json::from_str(payload_json)
                .unwrap_or(serde_json::Value::Object(serde_json::Map::new()));
            let interpolated_url = interpolate_command(url, &payload_value).into_owned();
            let interpolated_body = body
                .as_deref()
                .map(|b| interpolate_command(b, &payload_value).into_owned());
            ResolvedExecutor::Http {
                method: *method,
                url: interpolated_url,
                headers: headers.clone(),
                body: interpolated_body,
                follow_redirects: *follow_redirects,
            }
        }
    }
}

/// Everything the executor needs to run a command.
#[derive(Clone)]
pub struct ExecutionContext {
    /// The execution record ID (UUIDv7 string).
    pub execution_id: String,
    /// The hook slug, passed as SENDWORD_HOOK_SLUG env var.
    pub hook_slug: String,
    /// Which executor to dispatch to.
    pub executor: ResolvedExecutor,
    /// Additional environment variables for the process.
    pub env: HashMap<String, String>,
    /// Working directory. If None, inherits from the server process.
    pub cwd: Option<String>,
    /// Maximum execution time. Process is killed on expiry.
    pub timeout: Duration,
    /// Base directory for log files (e.g., "data/logs").
    pub logs_dir: String,
    /// Raw JSON payload from the trigger request. Set as SENDWORD_PAYLOAD
    /// env var and written to payload.json in the log directory.
    pub payload_json: String,
    /// Shared HTTP client for HTTP executor. Shell and script set this to None.
    /// reqwest::Client is cheaply clonable (Arc internally).
    pub http_client: Option<reqwest::Client>,
}

/// The outcome of an execution attempt.
pub struct ExecutionResult {
    /// Terminal status: Success, Failed, or TimedOut.
    pub status: ExecutionStatus,
    /// Process exit code. None if the process was killed or failed to spawn.
    pub exit_code: Option<i32>,
    /// Path to the log directory (data/logs/{execution_id}).
    pub log_dir: String,
}

/// Create the log directory and open stdout/stderr files for writing.
/// Returns (log_dir_path, stdout_file, stderr_file).
///
/// Files are opened in append mode so that retry attempts append to
/// existing log files rather than truncating them.
pub(crate) async fn prepare_log_files(
    logs_dir: &str,
    execution_id: &str,
    payload_json: &str,
) -> std::io::Result<(PathBuf, fs::File, fs::File)> {
    let log_dir = Path::new(logs_dir).join(execution_id);
    fs::create_dir_all(&log_dir).await?;

    // Write payload.json (uses write, not append, so retries overwrite
    // with identical content rather than duplicating)
    fs::write(log_dir.join("payload.json"), payload_json.as_bytes()).await?;

    let stdout_file = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(log_dir.join("stdout.log"))
        .await?;
    let stderr_file = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(log_dir.join("stderr.log"))
        .await?;

    Ok((log_dir, stdout_file, stderr_file))
}

/// Collect system environment variables that should be passed to child processes.
/// Returns only the vars that are actually set in the current process.
pub(crate) fn system_env_vars() -> HashMap<String, String> {
    const INHERIT_VARS: &[&str] = &["PATH", "HOME", "USER", "LANG"];

    let mut vars = HashMap::with_capacity(INHERIT_VARS.len());
    for &name in INHERIT_VARS {
        if let Ok(val) = std::env::var(name) {
            vars.insert(name.into(), val);
        }
    }
    vars
}

/// Dispatch to the appropriate executor based on the resolved executor type.
pub async fn run(pool: &SqlitePool, ctx: ExecutionContext) -> ExecutionResult {
    match &ctx.executor {
        ResolvedExecutor::Shell { command } => shell::run_shell(pool, &ctx, command).await,
        ResolvedExecutor::Script { path, runtime } => {
            script::run_script(pool, &ctx, path, *runtime).await
        }
        ResolvedExecutor::Http { .. } => {
            let client = ctx.http_client.clone().unwrap_or_default();
            http::run_http(pool, &ctx, &client).await
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::Db;
    use crate::models::execution;
    use sqlx::SqlitePool;

    // --- Unit tests ---

    #[tokio::test]
    async fn prepare_log_files_creates_directory_and_files() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let exec_id = "test-exec-001";

        let (log_dir, _stdout, _stderr) = prepare_log_files(logs_dir, exec_id, "{}")
            .await
            .expect("prepare_log_files");

        assert!(log_dir.exists());
        assert!(log_dir.join("stdout.log").exists());
        assert!(log_dir.join("stderr.log").exists());
    }

    #[test]
    fn system_env_vars_includes_path() {
        let vars = system_env_vars();
        assert!(
            vars.contains_key("PATH"),
            "PATH should be present in system env vars"
        );
    }

    #[test]
    fn system_env_vars_excludes_arbitrary_vars() {
        // Safety: test-only env var, unique name avoids collisions
        unsafe { std::env::set_var("SENDWORD_TEST_ARBITRARY_XYZ_999", "leaked") };
        let vars = system_env_vars();
        assert!(
            !vars.contains_key("SENDWORD_TEST_ARBITRARY_XYZ_999"),
            "arbitrary env vars should not be inherited"
        );
        unsafe { std::env::remove_var("SENDWORD_TEST_ARBITRARY_XYZ_999") };
    }

    #[test]
    fn resolve_shell_interpolates_payload_fields() {
        let resolved = resolve_executor(
            &ExecutorConfig::Shell {
                command: "deploy {{ action }}".into(),
            },
            r#"{"action":"prod"}"#,
        );

        let ResolvedExecutor::Shell { command } = resolved else {
            panic!("expected shell executor");
        };
        assert_eq!(command, "deploy 'prod'");
    }

    #[test]
    fn resolve_direct_script_runtime() {
        let resolved = resolve_executor(
            &ExecutorConfig::Script {
                path: "data/scripts/deploy.sh".into(),
            },
            "{}",
        );

        let ResolvedExecutor::Script { path, runtime } = resolved else {
            panic!("expected script executor");
        };
        assert_eq!(path, PathBuf::from("data/scripts/deploy.sh"));
        assert_eq!(runtime, ScriptRuntime::Direct);
    }

    #[test]
    fn resolve_javascript_script_runtime() {
        let resolved = resolve_executor(
            &ExecutorConfig::JavaScript {
                path: "data/scripts/deploy.js".into(),
            },
            "{}",
        );

        let ResolvedExecutor::Script { path, runtime } = resolved else {
            panic!("expected script executor");
        };
        assert_eq!(path, PathBuf::from("data/scripts/deploy.js"));
        assert_eq!(runtime, ScriptRuntime::JavaScript);
    }

    #[test]
    fn resolve_python_script_runtime() {
        let resolved = resolve_executor(
            &ExecutorConfig::Python {
                path: "data/scripts/deploy.py".into(),
            },
            "{}",
        );

        let ResolvedExecutor::Script { path, runtime } = resolved else {
            panic!("expected script executor");
        };
        assert_eq!(path, PathBuf::from("data/scripts/deploy.py"));
        assert_eq!(runtime, ScriptRuntime::Python);
    }

    #[test]
    fn resolve_http_interpolates_url_and_body() {
        let mut headers = HashMap::new();
        headers.insert("X-Test".into(), "static".into());
        let resolved = resolve_executor(
            &ExecutorConfig::Http {
                method: HttpMethod::Post,
                url: "https://example.test/{{ action }}".into(),
                headers: headers.clone(),
                body: Some(r#"{"action":"{{ action }}"}"#.into()),
                follow_redirects: false,
            },
            r#"{"action":"deploy"}"#,
        );

        let ResolvedExecutor::Http {
            method,
            url,
            headers: resolved_headers,
            body,
            follow_redirects,
        } = resolved
        else {
            panic!("expected http executor");
        };
        assert_eq!(method, HttpMethod::Post);
        assert_eq!(url, "https://example.test/'deploy'");
        assert_eq!(resolved_headers, headers);
        assert_eq!(body.as_deref(), Some(r#"{"action":"'deploy'"}"#));
        assert!(!follow_redirects);
    }

    #[tokio::test]
    async fn prepare_log_files_creates_nested_parents() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let nested = tmp.path().join("a").join("b").join("logs");
        let logs_dir = nested.to_str().expect("utf-8 path");
        let exec_id = "test-exec-002";

        let (log_dir, _stdout, _stderr) = prepare_log_files(logs_dir, exec_id, "{}")
            .await
            .expect("prepare_log_files");

        assert!(log_dir.exists());
        assert!(log_dir.join("stdout.log").exists());
        assert!(log_dir.join("stderr.log").exists());
    }

    // --- Integration test helpers ---

    async fn test_pool() -> SqlitePool {
        let db = Db::new_in_memory().await.expect("in-memory db");
        db.migrate().await.expect("migration");
        db.pool().clone()
    }

    /// Create a pending execution record and return a matching ExecutionContext.
    async fn setup_execution(pool: &SqlitePool, logs_dir: &str, command: &str) -> ExecutionContext {
        let exec = execution::create(
            pool,
            &execution::NewExecution {
                id: None,
                hook_slug: "test-hook",
                log_path: logs_dir,
                trigger_source: "127.0.0.1",
                request_payload: "{}",
                retry_of: None,
                status: None,
            },
        )
        .await
        .expect("create execution");

        ExecutionContext {
            execution_id: exec.id,
            hook_slug: "test-hook".into(),
            executor: ResolvedExecutor::Shell {
                command: command.into(),
            },
            env: HashMap::new(),
            cwd: None,
            timeout: Duration::from_secs(10),
            logs_dir: logs_dir.into(),
            payload_json: "{}".into(),
            http_client: None,
        }
    }

    /// Read a log file to a string.
    async fn read_log(logs_dir: &str, exec_id: &str, file: &str) -> String {
        let path = Path::new(logs_dir).join(exec_id).join(file);
        tokio::fs::read_to_string(path).await.unwrap_or_default()
    }

    // --- Integration tests ---

    #[tokio::test]
    async fn successful_command_returns_success() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let pool = test_pool().await;

        let ctx = setup_execution(&pool, logs_dir, "echo hello").await;
        let exec_id = ctx.execution_id.clone();

        let result = run(&pool, ctx).await;

        assert_eq!(result.status, ExecutionStatus::Success);
        assert_eq!(result.exit_code, Some(0));

        // Verify stdout.log
        let stdout = read_log(logs_dir, &exec_id, "stdout.log").await;
        assert_eq!(stdout.trim(), "hello");

        // Verify stderr.log is empty
        let stderr = read_log(logs_dir, &exec_id, "stderr.log").await;
        assert!(stderr.is_empty());

        // Verify DB record
        let exec = execution::get_by_id(&pool, &exec_id).await.expect("get");
        assert_eq!(exec.status, ExecutionStatus::Success);
        assert!(exec.started_at.is_some());
        assert!(exec.completed_at.is_some());
        assert_eq!(exec.exit_code, Some(0));
    }

    #[tokio::test]
    async fn failing_command_returns_failed_with_exit_code() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let pool = test_pool().await;

        let ctx = setup_execution(&pool, logs_dir, "exit 42").await;
        let exec_id = ctx.execution_id.clone();

        let result = run(&pool, ctx).await;

        assert_eq!(result.status, ExecutionStatus::Failed);
        assert_eq!(result.exit_code, Some(42));

        let exec = execution::get_by_id(&pool, &exec_id).await.expect("get");
        assert_eq!(exec.status, ExecutionStatus::Failed);
        assert_eq!(exec.exit_code, Some(42));
    }

    #[tokio::test]
    async fn stderr_output_is_captured() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let pool = test_pool().await;

        let ctx = setup_execution(&pool, logs_dir, "echo error >&2").await;
        let exec_id = ctx.execution_id.clone();

        let _result = run(&pool, ctx).await;

        let stderr = read_log(logs_dir, &exec_id, "stderr.log").await;
        assert_eq!(stderr.trim(), "error");
    }

    #[tokio::test]
    async fn timeout_kills_long_running_command() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let pool = test_pool().await;

        let mut ctx = setup_execution(&pool, logs_dir, "sleep 60").await;
        ctx.timeout = Duration::from_secs(1);
        let exec_id = ctx.execution_id.clone();

        let start = std::time::Instant::now();
        let result = run(&pool, ctx).await;
        let elapsed = start.elapsed();

        assert_eq!(result.status, ExecutionStatus::TimedOut);
        assert!(result.exit_code.is_none());
        assert!(
            elapsed < Duration::from_secs(5),
            "timeout test should complete quickly, took {elapsed:?}"
        );

        let exec = execution::get_by_id(&pool, &exec_id).await.expect("get");
        assert_eq!(exec.status, ExecutionStatus::TimedOut);
    }

    #[tokio::test]
    async fn hook_env_vars_are_passed_to_command() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let pool = test_pool().await;

        let mut ctx = setup_execution(&pool, logs_dir, "echo $MY_VAR").await;
        ctx.env.insert("MY_VAR".into(), "hello".into());
        let exec_id = ctx.execution_id.clone();

        let _result = run(&pool, ctx).await;

        let stdout = read_log(logs_dir, &exec_id, "stdout.log").await;
        assert_eq!(stdout.trim(), "hello");
    }

    #[tokio::test]
    async fn sendword_env_vars_are_set() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let pool = test_pool().await;

        let ctx = setup_execution(
            &pool,
            logs_dir,
            "echo $SENDWORD_EXECUTION_ID $SENDWORD_HOOK_SLUG",
        )
        .await;
        let exec_id = ctx.execution_id.clone();

        let _result = run(&pool, ctx).await;

        let stdout = read_log(logs_dir, &exec_id, "stdout.log").await;
        let parts: Vec<&str> = stdout.trim().split_whitespace().collect();
        assert_eq!(parts.len(), 2);
        assert_eq!(parts[0], exec_id);
        assert_eq!(parts[1], "test-hook");
    }

    #[tokio::test]
    async fn working_directory_is_respected() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let pool = test_pool().await;

        let work_dir = tempfile::TempDir::new().expect("work dir");
        let work_path = work_dir.path().canonicalize().expect("canonical path");

        let mut ctx = setup_execution(&pool, logs_dir, "pwd").await;
        ctx.cwd = Some(work_path.to_str().expect("utf-8").into());
        let exec_id = ctx.execution_id.clone();

        let _result = run(&pool, ctx).await;

        let stdout = read_log(logs_dir, &exec_id, "stdout.log").await;
        assert_eq!(stdout.trim(), work_path.to_str().expect("utf-8"));
    }

    #[tokio::test]
    async fn invalid_cwd_results_in_failed() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let pool = test_pool().await;

        let mut ctx = setup_execution(&pool, logs_dir, "echo should-not-run").await;
        ctx.cwd = Some("/nonexistent/path/that/does/not/exist".into());
        let exec_id = ctx.execution_id.clone();

        let result = run(&pool, ctx).await;

        assert_eq!(result.status, ExecutionStatus::Failed);

        let stderr = read_log(logs_dir, &exec_id, "stderr.log").await;
        assert!(
            !stderr.is_empty(),
            "stderr.log should contain spawn error message"
        );
    }

    #[tokio::test]
    async fn environment_is_clean_no_inherited_server_vars() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let pool = test_pool().await;

        // Safety: test-only env var, unique name avoids collisions
        unsafe { std::env::set_var("SENDWORD_TEST_UNIQUE_VAR_12345", "leaked") };

        let ctx = setup_execution(
            &pool,
            logs_dir,
            "echo ${SENDWORD_TEST_UNIQUE_VAR_12345:-clean}",
        )
        .await;
        let exec_id = ctx.execution_id.clone();

        let _result = run(&pool, ctx).await;

        unsafe { std::env::remove_var("SENDWORD_TEST_UNIQUE_VAR_12345") };

        let stdout = read_log(logs_dir, &exec_id, "stdout.log").await;
        assert_eq!(
            stdout.trim(),
            "clean",
            "server env vars should not leak to child process"
        );
    }

    #[tokio::test]
    async fn prepare_log_files_creates_payload_json() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let exec_id = "test-exec-payload";
        let payload = r#"{"test":true}"#;

        let (log_dir, _stdout, _stderr) = prepare_log_files(logs_dir, exec_id, payload)
            .await
            .expect("prepare_log_files");

        assert!(log_dir.join("payload.json").exists());
        let contents = tokio::fs::read_to_string(log_dir.join("payload.json"))
            .await
            .expect("read payload.json");
        assert_eq!(contents, payload);
    }

    #[tokio::test]
    async fn payload_json_file_is_written_to_log_dir() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let pool = test_pool().await;

        let mut ctx = setup_execution(&pool, logs_dir, "echo ok").await;
        ctx.payload_json = r#"{"action":"deploy","count":3}"#.into();
        let exec_id = ctx.execution_id.clone();

        let _result = run(&pool, ctx).await;

        let payload_path = Path::new(logs_dir).join(&exec_id).join("payload.json");
        let contents = tokio::fs::read_to_string(&payload_path)
            .await
            .expect("payload.json should exist");
        assert_eq!(contents, r#"{"action":"deploy","count":3}"#);
    }

    #[tokio::test]
    async fn sendword_payload_env_var_is_set() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let pool = test_pool().await;

        let mut ctx = setup_execution(&pool, logs_dir, "echo $SENDWORD_PAYLOAD").await;
        ctx.payload_json = r#"{"key":"value"}"#.into();
        let exec_id = ctx.execution_id.clone();

        let _result = run(&pool, ctx).await;

        let stdout = read_log(logs_dir, &exec_id, "stdout.log").await;
        assert_eq!(stdout.trim(), r#"{"key":"value"}"#);
    }

    #[tokio::test]
    async fn empty_payload_json_written_to_log_dir() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let pool = test_pool().await;

        let ctx = setup_execution(&pool, logs_dir, "echo ok").await;
        let exec_id = ctx.execution_id.clone();

        let _result = run(&pool, ctx).await;

        let payload_path = Path::new(logs_dir).join(&exec_id).join("payload.json");
        let contents = tokio::fs::read_to_string(&payload_path)
            .await
            .expect("payload.json should exist even for empty payload");
        assert_eq!(contents, "{}");
    }

    #[tokio::test]
    async fn sendword_payload_env_var_set_for_empty_payload() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let pool = test_pool().await;

        // setup_execution defaults payload_json to "{}"
        let ctx = setup_execution(&pool, logs_dir, "echo $SENDWORD_PAYLOAD").await;
        let exec_id = ctx.execution_id.clone();

        let _result = run(&pool, ctx).await;

        let stdout = read_log(logs_dir, &exec_id, "stdout.log").await;
        assert_eq!(stdout.trim(), "{}");
    }

    #[tokio::test]
    async fn payload_json_overwritten_not_appended_on_retry() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let logs_dir = tmp.path().to_str().expect("utf-8 path");
        let exec_id = "test-exec-overwrite";

        // Write payload.json twice with different content to simulate retry
        let payload_v1 = r#"{"version":1}"#;
        let payload_v2 = r#"{"version":2}"#;

        let _ = prepare_log_files(logs_dir, exec_id, payload_v1)
            .await
            .expect("first prepare");
        let (log_dir, _, _) = prepare_log_files(logs_dir, exec_id, payload_v2)
            .await
            .expect("second prepare");

        let contents = tokio::fs::read_to_string(log_dir.join("payload.json"))
            .await
            .expect("read payload.json");
        assert_eq!(
            contents, payload_v2,
            "payload.json should be overwritten, not appended"
        );
    }
}