orchestratectl 0.1.2

Rust CLI for orchestrating AI-agent workflows on a developer's machine.
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
//! Integration tests for `run create --kind <X>` materialization path.
//!
//! Uses a fake create.sh fixture so the test never touches tmux,
//! workmux, or the user's git tree. The fake script echoes a canned
//! JSON envelope using the current process PID as `agent_pid_hint` so
//! the supervisor's PID-liveness check passes.
//!
//! Coverage:
//! - All 8 kinds spawn cleanly and produce the expected node + payload.
//! - create.sh exit 2 → orchestratectl exit 2 with envelope code
//!   prefix `create_sh_error_`.
//! - Missing `--task`/`--prompt-file` is a structured user error.
//! - Top-level run writes node.created event and records `agent_pid`.

use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use std::process::Command;

use serde_json::Value;
use tempfile::TempDir;

mod common;
use common::TestHome;

const KINDS: &[&str] = &[
    "code",
    "spinoff",
    "orchestrated",
    "research",
    "technical-decision",
    "make-skill",
    "fan-out",
    "bugfix",
];

fn write_fake_create_sh(dir: &TempDir, stdout: &str, exit_code: i32) -> PathBuf {
    let path = dir.path().join("fake-create.sh");
    let body = format!("#!/bin/bash\ncat <<'EOF'\n{stdout}\nEOF\nexit {exit_code}\n");
    std::fs::write(&path, body).unwrap();
    let mut perms = std::fs::metadata(&path).unwrap().permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(&path, perms).unwrap();
    path
}

fn fake_success_stdout(kind: &str, pid: u32) -> String {
    format!(
        r#"{{"schema_version":1,"type":"{kind}","branch":"wt/test-{kind}","worktree_path":"/tmp/wt-{kind}","tmux_window":"🚀 wt/test-{kind}","agent_pid_hint":{pid},"workmux_session":"test"}}"#
    )
}

fn bin(home: &TempDir, script: &std::path::Path) -> Command {
    let mut c = Command::new(env!("CARGO_BIN_EXE_orchestratectl"));
    c.env("ORCHESTRATECTL_HOME", home.path());
    c.env("OCTL_CREATE_SH", script);
    // Intentionally do NOT set OCTL_TEST_SKIP_MATERIALIZE — these tests
    // exercise the real materialization path against the fake script.
    c
}

fn run_ok(cmd: &mut Command) -> Value {
    let out = cmd.output().expect("spawn");
    assert!(
        out.status.success(),
        "exit={:?} stderr={}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );
    serde_json::from_slice(&out.stdout).expect("stdout is JSON")
}

fn run_fail(cmd: &mut Command) -> (i32, Value) {
    let out = cmd.output().expect("spawn");
    assert!(!out.status.success(), "expected failure");
    let code = out.status.code().expect("exit code");
    let stderr = String::from_utf8(out.stderr).expect("utf8");
    let last = stderr.lines().last().expect("stderr line");
    let v: Value = serde_json::from_str(last).expect("error envelope JSON");
    (code, v)
}

#[test]
fn each_kind_spawns_and_emits_node_created() {
    for kind in KINDS {
        // `home` reaps the supervisor `run create` spawns when it drops,
        // before the run's TempDir is removed.
        let home = TestHome::new();
        let pid = std::process::id();
        let script = write_fake_create_sh(&home, &fake_success_stdout(kind, pid), 0);
        let v = run_ok(bin(&home, &script).args([
            "--output", "json", "run", "create", "--kind", kind, "--title", "smoke", "--task",
            "do work",
        ]));
        let data = &v["data"];
        assert_eq!(data["kind"], *kind, "kind in payload for {kind}: {data}");
        assert_eq!(data["node_id"], "n-0001", "node_id for {kind}");
        assert_eq!(data["branch"], format!("wt/test-{kind}"));
        assert_eq!(data["worktree_path"], format!("/tmp/wt-{kind}"));
        assert!(
            data["supervisor"].as_u64().is_some(),
            "supervisor pid for {kind}: {data}"
        );

        // events.jsonl should contain node.created with agent_pid set.
        let run_id = data["run_id"].as_str().unwrap();
        let events =
            std::fs::read_to_string(home.path().join("runs").join(run_id).join("events.jsonl"))
                .unwrap();
        let saw = events.lines().any(|l| {
            let v: Value = serde_json::from_str(l).unwrap();
            v["kind"] == "node.created" && v["data"]["agent_pid"].as_u64() == Some(u64::from(pid))
        });
        assert!(
            saw,
            "node.created with agent_pid missing for {kind}: {events}"
        );

        // `home` (a `TestHome`) SIGTERMs the spawned supervisor on drop —
        // before its TempDir removes the run dir — so the process is reaped
        // deterministically instead of being left to poll a vanished
        // directory.
    }
}

#[test]
fn missing_task_and_prompt_file_is_user_error() {
    let home = TempDir::new().unwrap();
    let script = write_fake_create_sh(&home, "", 0);
    let (code, v) = run_fail(bin(&home, &script).args([
        "--output", "json", "run", "create", "--kind", "spinoff", "--title", "x",
    ]));
    assert_eq!(code, 1);
    assert_eq!(v["error"]["code"], "missing-task-or-prompt-file");
}

#[test]
fn create_sh_exit_2_propagates_as_system_error() {
    let home = TempDir::new().unwrap();
    let path = home.path().join("fake-create.sh");
    let body = "#!/bin/bash\necho '{\"schema_version\":1,\"error\":{\"code\":\"workmux-missing\",\"message\":\"workmux not installed\"}}' >&2\nexit 2\n";
    std::fs::write(&path, body).unwrap();
    let mut perms = std::fs::metadata(&path).unwrap().permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(&path, perms).unwrap();
    let (code, v) = run_fail(bin(&home, &path).args([
        "--output", "json", "run", "create", "--kind", "spinoff", "--title", "x", "--task", "do",
    ]));
    assert_eq!(
        code, 2,
        "create.sh exit 2 should map to orchestratectl exit 2"
    );
    assert!(
        v["error"]["code"]
            .as_str()
            .unwrap()
            .starts_with("create_sh_error_"),
        "expected create_sh_error_ prefix: {v}"
    );
}

/// A fixture create.sh that records its own argv to `argv_path` (one arg per
/// line) before emitting the canned success envelope. Lets a test assert which
/// flags `run create` forwarded to create.sh.
fn write_argv_recording_create_sh(
    dir: &TempDir,
    argv_path: &std::path::Path,
    stdout: &str,
) -> PathBuf {
    let path = dir.path().join("argv-create.sh");
    let body = format!(
        "#!/bin/bash\nprintf '%s\\n' \"$@\" > '{}'\ncat <<'EOF'\n{stdout}\nEOF\nexit 0\n",
        argv_path.display()
    );
    std::fs::write(&path, body).unwrap();
    let mut perms = std::fs::metadata(&path).unwrap().permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(&path, perms).unwrap();
    path
}

#[test]
fn headless_forwards_parent_session_to_create_sh() {
    // `home` reaps the spawned supervisor on drop, before the run dir vanishes.
    let home = TestHome::new();
    let argv = home.path().join("create-argv.txt");
    let script = write_argv_recording_create_sh(
        &home,
        &argv,
        &fake_success_stdout("spinoff", std::process::id()),
    );
    run_ok(bin(&home, &script).args([
        "--output",
        "json",
        "run",
        "create",
        "--kind",
        "spinoff",
        "--title",
        "hl",
        "--task",
        "do work",
        "--headless",
    ]));

    let recorded = std::fs::read_to_string(&argv).expect("create.sh recorded its argv");
    let forwarded: Vec<&str> = recorded.lines().collect();
    // `--headless` with no explicit name resolves to the default `headless`
    // session, forwarded as the `--parent-session <name>` pair.
    let pos = forwarded
        .iter()
        .position(|a| *a == "--parent-session")
        .unwrap_or_else(|| panic!("--parent-session not forwarded; argv={forwarded:?}"));
    assert_eq!(
        forwarded.get(pos + 1).copied(),
        Some("headless"),
        "--parent-session value should be the default headless session; argv={forwarded:?}"
    );
}

#[test]
fn foreground_omits_parent_session_flag() {
    let home = TestHome::new();
    let argv = home.path().join("create-argv.txt");
    let script = write_argv_recording_create_sh(
        &home,
        &argv,
        &fake_success_stdout("spinoff", std::process::id()),
    );
    run_ok(bin(&home, &script).args([
        "--output", "json", "run", "create", "--kind", "spinoff", "--title", "fg", "--task",
        "do work",
    ]));

    let recorded = std::fs::read_to_string(&argv).expect("create.sh recorded its argv");
    assert!(
        !recorded.lines().any(|a| a == "--parent-session"),
        "foreground spawn must not forward --parent-session; argv={recorded:?}"
    );
}

#[test]
fn source_branch_forwards_base_flag_to_create_sh() {
    // The create.rs path must hand `--source-branch <branch>` to create.sh as
    // `--base <branch>` so the worktree forks from the named branch (e.g. an
    // orchestrate integration branch) rather than workmux's default base.
    let home = TestHome::new();
    let argv = home.path().join("create-argv.txt");
    let script = write_argv_recording_create_sh(
        &home,
        &argv,
        &fake_success_stdout("spinoff", std::process::id()),
    );
    run_ok(bin(&home, &script).args([
        "--output",
        "json",
        "run",
        "create",
        "--kind",
        "spinoff",
        "--title",
        "sb",
        "--task",
        "do work",
        "--source-branch",
        "orchestrate/integration",
    ]));

    let recorded = std::fs::read_to_string(&argv).expect("create.sh recorded its argv");
    let forwarded: Vec<&str> = recorded.lines().collect();
    let pos = forwarded
        .iter()
        .position(|a| *a == "--base")
        .unwrap_or_else(|| panic!("--base not forwarded; argv={forwarded:?}"));
    assert_eq!(
        forwarded.get(pos + 1).copied(),
        Some("orchestrate/integration"),
        "--base value should be the source branch; argv={forwarded:?}"
    );
}

#[test]
fn no_source_branch_omits_base_flag() {
    let home = TestHome::new();
    let argv = home.path().join("create-argv.txt");
    let script = write_argv_recording_create_sh(
        &home,
        &argv,
        &fake_success_stdout("spinoff", std::process::id()),
    );
    run_ok(bin(&home, &script).args([
        "--output", "json", "run", "create", "--kind", "spinoff", "--title", "nosb", "--task",
        "do work",
    ]));

    let recorded = std::fs::read_to_string(&argv).expect("create.sh recorded its argv");
    assert!(
        !recorded.lines().any(|a| a == "--base"),
        "run without --source-branch must not forward --base; argv={recorded:?}"
    );
}

#[test]
fn task_writes_prompt_file_in_run_dir() {
    // `home` reaps the supervisor `run create` spawns when it drops, before
    // the run dir is removed.
    let home = TestHome::new();
    let script = write_fake_create_sh(
        &home,
        &fake_success_stdout("spinoff", std::process::id()),
        0,
    );
    let v = run_ok(bin(&home, &script).args([
        "--output",
        "json",
        "run",
        "create",
        "--kind",
        "spinoff",
        "--title",
        "p",
        "--task",
        "investigate the bug",
    ]));
    let run_id = v["data"]["run_id"].as_str().unwrap();
    let prompt =
        std::fs::read_to_string(home.path().join("runs").join(run_id).join("prompt.md")).unwrap();
    assert_eq!(prompt, "investigate the bug");
}

/// Spawn a top-level `--kind orchestrate` driver run and return its run id.
/// The driver is skip-materialize (no create.sh, no supervisor — it runs in
/// the user's main conversation), so it makes a clean parent for child-spawn
/// tests without booting any process.
fn spawn_parent_orchestrate(home: &TempDir, script: &std::path::Path) -> String {
    let v = run_ok(bin(home, script).args([
        "--output",
        "json",
        "run",
        "create",
        "--kind",
        "orchestrate",
        "--title",
        "driver",
        "--task",
        "drive the dag",
    ]));
    v["data"]["run_id"].as_str().unwrap().to_string()
}

/// Count `child.spawned` events in a run's event log.
fn count_child_spawned(home: &TempDir, run_id: &str) -> usize {
    let path = home.path().join("runs").join(run_id).join("events.jsonl");
    let Ok(events) = std::fs::read_to_string(path) else {
        return 0;
    };
    events
        .lines()
        .filter(|l| serde_json::from_str::<Value>(l).is_ok_and(|v| v["kind"] == "child.spawned"))
        .count()
}

#[test]
fn failed_child_spawn_leaves_no_phantom_child() {
    // Regression for `failed-spawn-leaves-phantom-child`: a create.sh failure
    // during an orchestrated child spawn must be transactional — no
    // `child.spawned` on the parent and no child run dir left behind in
    // `pending`. (Before the fix, the parent log carried a child.spawned and a
    // 0-node phantom child sat in `pending` forever.)
    let home = TestHome::new();
    let ok_script = write_fake_create_sh(&home, &fake_success_stdout("orchestrate", 0), 0);
    let parent = spawn_parent_orchestrate(&home, &ok_script);

    // A create.sh that fails the way the original bug did (exit 2, error
    // envelope on stderr) instead of materializing the child.
    let fail_path = home.path().join("fail-create.sh");
    std::fs::write(
        &fail_path,
        "#!/bin/bash\necho '{\"schema_version\":1,\"error\":{\"code\":\"workmux-add-failed\",\"message\":\"boom\"}}' >&2\nexit 2\n",
    )
    .unwrap();
    let mut perms = std::fs::metadata(&fail_path).unwrap().permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(&fail_path, perms).unwrap();

    // Snapshot the runs dir so we can prove the failed spawn created no new run.
    let runs_dir = home.path().join("runs");
    let before: std::collections::BTreeSet<_> = std::fs::read_dir(&runs_dir)
        .unwrap()
        .map(|e| e.unwrap().file_name())
        .collect();

    let (code, v) = run_fail(bin(&home, &fail_path).args([
        "--output",
        "json",
        "run",
        "create",
        "--kind",
        "orchestrated",
        "--title",
        "doomed child",
        "--task",
        "do work",
        "--parent-run-id",
        &parent,
        "--parent-node-id",
        "n-0001",
    ]));
    assert_eq!(code, 2, "create.sh exit 2 should surface as exit 2: {v}");
    assert!(
        v["error"]["code"]
            .as_str()
            .unwrap()
            .starts_with("create_sh_error_"),
        "expected create_sh_error_ prefix: {v}"
    );

    // (a) No child.spawned landed on the parent.
    assert_eq!(
        count_child_spawned(&home, &parent),
        0,
        "failed spawn must not emit child.spawned on the parent"
    );

    // (b) No new child run dir exists — the orphan was cleaned up.
    let after: std::collections::BTreeSet<_> = std::fs::read_dir(&runs_dir)
        .unwrap()
        .map(|e| e.unwrap().file_name())
        .collect();
    assert_eq!(
        before, after,
        "failed child spawn must leave no new run dir behind"
    );
}

#[test]
fn successful_child_spawn_emits_child_spawned() {
    // Regression guard for the happy path: a successful orchestrated child
    // spawn still emits exactly one `child.spawned` on the parent, the child
    // run is materialized (node.created + autonomous lifecycle), and the child
    // run dir exists.
    let home = TestHome::new();
    let script = write_fake_create_sh(
        &home,
        &fake_success_stdout("orchestrated", std::process::id()),
        0,
    );
    let parent = spawn_parent_orchestrate(&home, &script);

    let v = run_ok(bin(&home, &script).args([
        "--output",
        "json",
        "run",
        "create",
        "--kind",
        "orchestrated",
        "--title",
        "live child",
        "--task",
        "do work",
        "--parent-run-id",
        &parent,
        "--parent-node-id",
        "n-0001",
    ]));
    let child_run_id = v["data"]["run_id"].as_str().unwrap();
    assert_eq!(v["data"]["node_id"], "n-0001");
    assert_eq!(v["data"]["parent_run_id"], parent);
    assert_eq!(v["data"]["lifecycle"], "autonomous");

    // Exactly one child.spawned on the parent, referencing this child.
    let parent_events =
        std::fs::read_to_string(home.path().join("runs").join(&parent).join("events.jsonl"))
            .unwrap();
    let spawned: Vec<Value> = parent_events
        .lines()
        .map(|l| serde_json::from_str::<Value>(l).unwrap())
        .filter(|v| v["kind"] == "child.spawned")
        .collect();
    assert_eq!(
        spawned.len(),
        1,
        "expected one child.spawned: {parent_events}"
    );
    assert_eq!(spawned[0]["data"]["child_run_id"], child_run_id);
    assert_eq!(spawned[0]["data"]["child_kind"], "orchestrated");
    assert_eq!(spawned[0]["node_id"], "n-0001");

    // The child run is materialized: its dir exists and carries node.created.
    let child_events = std::fs::read_to_string(
        home.path()
            .join("runs")
            .join(child_run_id)
            .join("events.jsonl"),
    )
    .unwrap();
    assert!(
        child_events
            .lines()
            .any(|l| serde_json::from_str::<Value>(l).is_ok_and(|v| v["kind"] == "node.created")),
        "child run must have node.created: {child_events}"
    );
}