leviath-cli 0.3.8

Command-line interface for Leviath agent framework
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
//! `lev msg` / `lev cancel` / `lev pause` / `lev resume` - control operations
//! on a running agent in the shared-world daemon.
//!
//! Each sends a control request over the daemon socket and reports the boolean
//! outcome. The request/response cores are tested here; the socket-path
//! resolution + connect live in the binary behind [`crate::dispatch::RiskyExecutors`].

use anyhow::bail;
use leviath_core::interaction::{
    ApprovalScope, InteractionKind, InteractionRequest, InteractionResponse,
};
use leviath_runtime::control_socket::{ControlClient, ControlRequest, ControlResponse};

/// Arguments for `lev msg`.
#[derive(clap::Args, Debug, Clone)]
pub struct MsgArgs {
    /// The target agent id.
    pub agent_id: String,
    /// The message to deliver.
    pub content: String,
}

/// Arguments for `lev cancel`.
#[derive(clap::Args, Debug, Clone)]
pub struct CancelArgs {
    /// The run id to cancel.
    pub run_id: String,
    /// Terminate the run's on-disk state directly, without asking the daemon.
    ///
    /// Use when the daemon is gone or unresponsive. The run is recorded
    /// `Cancelled` so nothing lists it as live; if a daemon is in fact still
    /// driving it, restart the daemon so it picks up the new state.
    #[arg(long)]
    pub force: bool,
}

/// Arguments for `lev pause`.
#[derive(clap::Args, Debug, Clone)]
pub struct PauseArgs {
    /// The run id to pause.
    pub run_id: String,
}

/// Arguments for `lev resume`.
#[derive(clap::Args, Debug, Clone)]
pub struct ResumeArgs {
    /// The run id to resume.
    pub run_id: String,
}

/// Arguments for `lev respond` - answer a pending `ask_user` interaction the
/// daemon is holding, or (with no `request_id`) list the open interactions.
#[derive(clap::Args, Debug, Clone)]
pub struct RespondArgs {
    /// The interaction request id to answer. Omit to list open interactions.
    pub request_id: Option<String>,
    /// Free-text (or edited) answer value.
    pub value: Option<String>,
    /// Answer a multiple-choice interaction by 0-based option index.
    #[arg(long)]
    pub choice: Option<usize>,
    /// Approve a tool-approval / confirm interaction.
    #[arg(long, conflicts_with = "deny")]
    pub approve: bool,
    /// Deny a tool-approval / confirm interaction.
    #[arg(long)]
    pub deny: bool,
    /// With `--approve`, allow what this call runs for the rest of the run.
    #[arg(long, visible_alias = "run")]
    pub session: bool,
    /// With `--approve`, allow what this call runs until the run leaves the
    /// current stage.
    #[arg(long, conflicts_with = "session")]
    pub stage: bool,
    /// Report open interactions (or the outcome of answering one) as JSON.
    /// This is how an unattended caller finds the questions it has to answer.
    #[arg(long)]
    pub json: bool,
}

/// One open interaction in `lev respond --json`.
///
/// The whole request rather than the four fields the prose listing has room
/// for: `tool_arguments` and `body` are exactly what a caller deciding whether
/// to approve needs, and neither appears in the human listing.
#[derive(serde::Serialize)]
struct OpenInteraction<'a> {
    /// The agent holding the question, for a caller polling several runs.
    agent_id: &'a str,
    #[serde(flatten)]
    request: &'a InteractionRequest,
}

/// Send `request` and report the boolean outcome: `ok` prints `applied_msg`, a
/// `false` outcome the `not_found_msg`. A non-`Ok` response or a connect failure
/// is an error.
async fn send_bool(
    client: &ControlClient,
    request: ControlRequest,
    applied_msg: &str,
    not_found_msg: &str,
) -> anyhow::Result<()> {
    match client.request(&request).await {
        Ok(ControlResponse::Ok { ok: true }) => {
            println!("{applied_msg}");
            Ok(())
        }
        Ok(ControlResponse::Ok { ok: false }) => bail!("{not_found_msg}"),
        Ok(other) => bail!("unexpected daemon response: {other:?}"),
        Err(e) => bail!("the leviath daemon is not reachable ({e}); start it with `lev daemon`"),
    }
}

/// `lev msg`: deliver a message to a running agent.
pub async fn send_message(client: &ControlClient, args: &MsgArgs) -> anyhow::Result<()> {
    send_bool(
        client,
        ControlRequest::Message {
            agent_id: args.agent_id.clone(),
            content: args.content.clone(),
            target_region: None,
        },
        "message delivered",
        "no agent accepted the message",
    )
    .await
}

/// `lev pause`: park a run. The daemon refuses (`ok: false`) when the run does
/// not exist or is not in a pausable state (waiting on input, or finished).
pub async fn pause_run(client: &ControlClient, args: &PauseArgs) -> anyhow::Result<()> {
    send_bool(
        client,
        ControlRequest::Pause {
            run_id: args.run_id.clone(),
        },
        "paused",
        "no such run, or it is not pausable in its current state",
    )
    .await
}

/// `lev resume`: un-pause a run.
pub async fn resume_run(client: &ControlClient, args: &ResumeArgs) -> anyhow::Result<()> {
    send_bool(
        client,
        ControlRequest::Resume {
            run_id: args.run_id.clone(),
        },
        "resumed",
        "no such run, or it is not paused",
    )
    .await
}

/// `lev cancel`: cancel a run.
///
/// A kill must always be possible, so this never depends on the daemon being
/// reachable. `--force` goes straight to the run's on-disk state; otherwise the
/// daemon is asked first (it can also stop the work, not just record the
/// outcome) and the on-disk write is the fallback when it can't be reached or
/// doesn't answer in time.
pub async fn cancel_run(client: &ControlClient, args: &CancelArgs) -> anyhow::Result<()> {
    if args.force {
        return report_forced(
            crate::runstate::force_cancel(&args.run_id),
            &args.run_id,
            None,
        );
    }
    match client
        .request(&ControlRequest::Cancel {
            run_id: args.run_id.clone(),
        })
        .await
    {
        Ok(ControlResponse::Ok { ok: true }) => {
            println!("cancelled");
            Ok(())
        }
        Ok(ControlResponse::Ok { ok: false }) => bail!("no such run"),
        Ok(other) => bail!("unexpected daemon response: {other:?}"),
        // The daemon is down, wedged, or too busy to answer. Terminate the run on
        // disk ourselves rather than leave the user with nothing.
        Err(e) => report_forced(
            crate::runstate::force_cancel(&args.run_id),
            &args.run_id,
            Some(e),
        ),
    }
}

/// Report the outcome of an on-disk cancel. `daemon_error` is set when this was
/// a fallback rather than an explicit `--force`, and is included so the user
/// knows why the daemon wasn't used.
fn report_forced(
    outcome: crate::runstate::ForceCancelOutcome,
    run_id: &str,
    daemon_error: Option<std::io::Error>,
) -> anyhow::Result<()> {
    use crate::runstate::ForceCancelOutcome as O;
    let why = match &daemon_error {
        Some(e) => format!(" (the daemon did not answer: {e})"),
        None => String::new(),
    };
    match outcome {
        O::Terminated => {
            println!(
                "cancelled '{run_id}' on disk{why}; if a daemon is still running, \
                 restart it so it picks up the change"
            );
            Ok(())
        }
        O::AlreadyTerminal => {
            println!("'{run_id}' had already finished; nothing to cancel");
            Ok(())
        }
        O::NoSuchRun => match daemon_error {
            Some(e) => bail!(
                "the leviath daemon is not reachable ({e}), and there is no run '{run_id}' on disk"
            ),
            None => bail!("no such run"),
        },
        O::WriteFailed => bail!("could not write '{run_id}' metadata to record the cancel"),
    }
}

/// A short human label for an interaction kind (used by the `lev respond` list).
fn kind_label(kind: &InteractionKind) -> &'static str {
    match kind {
        InteractionKind::FreeText => "free-text",
        InteractionKind::MultipleChoice => "choice",
        InteractionKind::Confirm => "confirm",
        InteractionKind::ToolApproval => "tool-approval",
        InteractionKind::EditText => "edit-text",
    }
}

/// Render one open interaction as a multi-line listing entry.
fn format_interaction(agent_id: &str, req: &InteractionRequest) -> String {
    let mut s = format!(
        "{}  [{}]  agent={}  stage={}\n  {}",
        req.id,
        kind_label(&req.kind),
        agent_id,
        req.stage_name,
        req.prompt
    );
    for (i, opt) in req.options.iter().enumerate() {
        s.push_str(&format!("\n    {i}) {opt}"));
    }
    if let Some(tool) = &req.tool_name {
        s.push_str(&format!("\n    tool: {tool}"));
    }
    s
}

/// Build the [`InteractionResponse`] implied by the CLI flags. Approve/deny wins,
/// then an explicit `--choice`, otherwise a free-text value (empty if omitted).
fn build_response(request_id: &str, args: &RespondArgs) -> InteractionResponse {
    if args.approve || args.deny {
        let scope = match (args.session, args.stage) {
            (true, _) => ApprovalScope::Run,
            (_, true) => ApprovalScope::Stage,
            _ => ApprovalScope::Once,
        };
        InteractionResponse::approval(request_id, args.approve, scope)
    } else if let Some(index) = args.choice {
        InteractionResponse::choice(request_id, index)
    } else {
        InteractionResponse::text(request_id, args.value.clone().unwrap_or_default())
    }
}

/// List the interactions the daemon is currently holding.
async fn list_interactions(client: &ControlClient, json: bool) -> anyhow::Result<()> {
    match client.request(&ControlRequest::ListInteractions).await {
        Ok(ControlResponse::Interactions { interactions }) => {
            if json {
                let open: Vec<OpenInteraction<'_>> = interactions
                    .iter()
                    .map(|(agent_id, request)| OpenInteraction { agent_id, request })
                    .collect();
                // Nothing open is an empty array, not a sentence: a caller
                // polling this branches on length, not on prose.
                println!(
                    "{}",
                    serde_json::to_string_pretty(&open).expect("an interaction listing serializes")
                );
                return Ok(());
            }
            if interactions.is_empty() {
                println!("no open interactions");
            } else {
                for (agent_id, req) in &interactions {
                    println!("{}", format_interaction(agent_id, req));
                }
            }
            Ok(())
        }
        Ok(other) => bail!("unexpected daemon response: {other:?}"),
        Err(e) => bail!("the leviath daemon is not reachable ({e}); start it with `lev daemon`"),
    }
}

/// `lev respond`: answer a pending interaction, or list open ones when no
/// `request_id` is given.
pub async fn respond(client: &ControlClient, args: &RespondArgs) -> anyhow::Result<()> {
    match &args.request_id {
        None => list_interactions(client, args.json).await,
        Some(request_id) => {
            // A failed answer stays an error (non-zero exit plus the message on
            // stderr), so `--json` only changes the success line.
            let applied = match args.json {
                // Serialized, not interpolated: a request id carrying a quote
                // would otherwise emit JSON that does not parse.
                true => {
                    serde_json::json!({ "answered": true, "request_id": request_id }).to_string()
                }
                false => "answered".to_string(),
            };
            send_bool(
                client,
                ControlRequest::AnswerInteraction {
                    response: build_response(request_id, args),
                },
                &applied,
                "no such open interaction",
            )
            .await
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use leviath_runtime::control_socket::{ControlId, bind_control_listener, control_id};
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
    use tokio::task::JoinHandle;

    /// Bind a control listener at a fresh id under `dir` and serve one canned
    /// response, returning the id clients connect to and the server task.
    fn fake_daemon(dir: &std::path::Path, response_line: String) -> (ControlId, JoinHandle<()>) {
        let id = control_id(dir);
        let mut listener = bind_control_listener(&id).unwrap();
        let handle = tokio::spawn(async move {
            let stream = listener
                .accept()
                .await
                .expect("accept succeeds")
                .expect("our own connection is admitted");
            let (read_half, mut write_half) = tokio::io::split(stream);
            let mut lines = BufReader::new(read_half).lines();
            let _request = lines.next_line().await.unwrap();
            write_half
                .write_all(response_line.as_bytes())
                .await
                .unwrap();
            write_half.write_all(b"\n").await.unwrap();
        });
        (id, handle)
    }

    /// Run `op` against a fake daemon that replies `response_line`.
    async fn with_daemon<F, Fut>(response_line: impl Into<String>, op: F) -> anyhow::Result<()>
    where
        F: FnOnce(ControlClient) -> Fut,
        Fut: std::future::Future<Output = anyhow::Result<()>>,
    {
        let dir = tempfile::tempdir().unwrap();
        let (id, server) = fake_daemon(dir.path(), response_line.into());
        let result = op(ControlClient::new(id)).await;
        server.await.unwrap();
        result
    }

    fn msg_args() -> MsgArgs {
        MsgArgs {
            agent_id: "a".to_string(),
            content: "hi".to_string(),
        }
    }

    #[tokio::test]
    async fn message_applied() {
        let r = with_daemon(r#"{"result":"ok","ok":true}"#, |c| async move {
            send_message(&c, &msg_args()).await
        })
        .await;
        assert!(r.is_ok());
    }

    #[tokio::test]
    async fn message_not_delivered() {
        let r = with_daemon(r#"{"result":"ok","ok":false}"#, |c| async move {
            send_message(&c, &msg_args()).await
        })
        .await;
        assert!(r.unwrap_err().to_string().contains("no agent accepted"));
    }

    #[tokio::test]
    async fn pause_applied() {
        let r = with_daemon(r#"{"result":"ok","ok":true}"#, |c| async move {
            pause_run(
                &c,
                &PauseArgs {
                    run_id: "r".to_string(),
                },
            )
            .await
        })
        .await;
        assert!(r.is_ok());
    }

    #[tokio::test]
    async fn pause_refused() {
        let r = with_daemon(r#"{"result":"ok","ok":false}"#, |c| async move {
            pause_run(
                &c,
                &PauseArgs {
                    run_id: "r".to_string(),
                },
            )
            .await
        })
        .await;
        assert!(r.unwrap_err().to_string().contains("not pausable"));
    }

    #[tokio::test]
    async fn resume_applied() {
        let r = with_daemon(r#"{"result":"ok","ok":true}"#, |c| async move {
            resume_run(
                &c,
                &ResumeArgs {
                    run_id: "r".to_string(),
                },
            )
            .await
        })
        .await;
        assert!(r.is_ok());
    }

    #[tokio::test]
    async fn resume_refused() {
        let r = with_daemon(r#"{"result":"ok","ok":false}"#, |c| async move {
            resume_run(
                &c,
                &ResumeArgs {
                    run_id: "r".to_string(),
                },
            )
            .await
        })
        .await;
        assert!(r.unwrap_err().to_string().contains("not paused"));
    }

    #[tokio::test]
    async fn cancel_applied() {
        let r = with_daemon(r#"{"result":"ok","ok":true}"#, |c| async move {
            cancel_run(
                &c,
                &CancelArgs {
                    run_id: "r".to_string(),
                    force: false,
                },
            )
            .await
        })
        .await;
        assert!(r.is_ok());
    }

    #[tokio::test]
    async fn cancel_unknown_run() {
        let r = with_daemon(r#"{"result":"ok","ok":false}"#, |c| async move {
            cancel_run(
                &c,
                &CancelArgs {
                    run_id: "r".to_string(),
                    force: false,
                },
            )
            .await
        })
        .await;
        assert!(r.unwrap_err().to_string().contains("no such run"));
    }

    #[tokio::test]
    async fn unexpected_response_is_an_error() {
        // Both the `send_bool` path (`lev msg`) and `cancel_run`'s own match
        // reject a response shape they didn't ask for.
        let r = with_daemon(r#"{"result":"spawned","run_id":"x"}"#, |c| async move {
            send_message(&c, &msg_args()).await
        })
        .await;
        assert!(r.unwrap_err().to_string().contains("unexpected"));

        let r = with_daemon(r#"{"result":"spawned","run_id":"x"}"#, |c| async move {
            cancel_run(
                &c,
                &CancelArgs {
                    run_id: "r".to_string(),
                    force: false,
                },
            )
            .await
        })
        .await;
        assert!(r.unwrap_err().to_string().contains("unexpected"));
    }

    /// `lev msg` has no on-disk fallback - an unreachable daemon is simply an
    /// error, unlike `lev cancel`.
    #[tokio::test]
    async fn message_to_an_unreachable_daemon_is_an_error() {
        let dir = tempfile::tempdir().unwrap();
        let client = ControlClient::new(control_id(&dir.path().join("no-daemon")));
        let err = send_message(&client, &msg_args()).await.unwrap_err();
        assert!(err.to_string().contains("not reachable"));
    }

    /// A run directory that cannot be rewritten is reported as such, rather than
    /// as a successful cancel.
    #[tokio::test]
    async fn forcing_a_run_whose_metadata_cannot_be_written_reports_the_failure() {
        crate::runstate::with_isolated_runs_dir_async("ctl-force-unwritable", |_base| async {
            let dir = crate::runstate::run_dir("blocked-1");
            std::fs::create_dir_all(dir.join("meta.json")).unwrap();

            let err = cancel_run(
                &ControlClient::new(control_id(std::path::Path::new("/nonexistent"))),
                &CancelArgs {
                    run_id: "blocked-1".to_string(),
                    force: true,
                },
            )
            .await
            .unwrap_err();
            assert!(err.to_string().contains("could not write"), "got: {err}");
        })
        .await;
    }

    #[tokio::test]
    async fn not_reachable_is_an_error() {
        let dir = tempfile::tempdir().unwrap();
        let client = ControlClient::new(control_id(&dir.path().join("no-daemon")));
        let err = cancel_run(
            &client,
            &CancelArgs {
                run_id: "r".to_string(),
                force: false,
            },
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("not reachable"));
    }

    /// Write a live-looking run into the (isolated) runs dir.
    fn seed_live_run(run_id: &str) {
        crate::runstate::create_run(&crate::runstate::RunMeta {
            status: crate::runstate::RunStatus::Running,
            ..crate::runstate::RunMeta::new(
                run_id.into(),
                "a".into(),
                "/p".into(),
                "t".into(),
                None,
                "/w".into(),
                1,
            )
        })
        .unwrap();
    }

    fn status_of(run_id: &str) -> crate::runstate::RunStatus {
        crate::runstate::read_meta(run_id).unwrap().status
    }

    /// `--force` never contacts the daemon, so a kill stays possible when the
    /// daemon is dead, wedged, or was never started.
    #[tokio::test]
    async fn force_cancels_on_disk_without_a_daemon() {
        crate::runstate::with_isolated_runs_dir_async("ctl-force-cancel", |_base| async {
            seed_live_run("stuck-1");
            let dir = tempfile::tempdir().unwrap();
            // A socket path with nothing listening on it.
            let client = ControlClient::new(control_id(&dir.path().join("no-daemon")));

            cancel_run(
                &client,
                &CancelArgs {
                    run_id: "stuck-1".to_string(),
                    force: true,
                },
            )
            .await
            .expect("forced cancel succeeds with no daemon");

            assert_eq!(status_of("stuck-1"), crate::runstate::RunStatus::Cancelled);
        })
        .await;
    }

    /// Without `--force`, an unreachable daemon falls back to the on-disk write
    /// rather than leaving the user with an error and a run still marked live.
    #[tokio::test]
    async fn an_unreachable_daemon_falls_back_to_cancelling_on_disk() {
        crate::runstate::with_isolated_runs_dir_async("ctl-fallback-cancel", |_base| async {
            seed_live_run("stuck-2");
            let dir = tempfile::tempdir().unwrap();
            let client = ControlClient::new(control_id(&dir.path().join("no-daemon")));

            cancel_run(
                &client,
                &CancelArgs {
                    run_id: "stuck-2".to_string(),
                    force: false,
                },
            )
            .await
            .expect("the fallback succeeds");

            assert_eq!(status_of("stuck-2"), crate::runstate::RunStatus::Cancelled);
        })
        .await;
    }

    /// Forcing a run that already finished is reported, not treated as a failure.
    #[tokio::test]
    async fn forcing_an_already_finished_run_is_not_an_error() {
        crate::runstate::with_isolated_runs_dir_async("ctl-force-terminal", |_base| async {
            crate::runstate::create_run(&crate::runstate::RunMeta {
                status: crate::runstate::RunStatus::Complete,
                ..crate::runstate::RunMeta::new(
                    "done-1".into(),
                    "a".into(),
                    "/p".into(),
                    "t".into(),
                    None,
                    "/w".into(),
                    1,
                )
            })
            .unwrap();

            cancel_run(
                &ControlClient::new(control_id(std::path::Path::new("/nonexistent"))),
                &CancelArgs {
                    run_id: "done-1".to_string(),
                    force: true,
                },
            )
            .await
            .expect("already-finished is reported, not an error");

            assert_eq!(
                status_of("done-1"),
                crate::runstate::RunStatus::Complete,
                "and the recorded outcome is left intact"
            );
        })
        .await;
    }

    /// Forcing an id that names no run at all is still an honest failure.
    #[tokio::test]
    async fn forcing_an_unknown_run_reports_no_such_run() {
        crate::runstate::with_isolated_runs_dir_async("ctl-force-missing", |_base| async {
            let err = cancel_run(
                &ControlClient::new(control_id(std::path::Path::new("/nonexistent"))),
                &CancelArgs {
                    run_id: "never-existed".to_string(),
                    force: true,
                },
            )
            .await
            .unwrap_err();
            assert!(err.to_string().contains("no such run"), "got: {err}");
        })
        .await;
    }

    // ─── lev respond ──────────────────────────────────────────────────────────

    fn respond_args() -> RespondArgs {
        RespondArgs {
            request_id: Some("q1".to_string()),
            value: None,
            choice: None,
            approve: false,
            deny: false,
            session: false,
            stage: false,
            json: false,
        }
    }

    #[test]
    fn build_response_free_text_uses_value_or_empty() {
        let with_value = build_response(
            "q1",
            &RespondArgs {
                value: Some("hello".to_string()),
                ..respond_args()
            },
        );
        assert_eq!(with_value, InteractionResponse::text("q1", "hello"));
        // Missing value → empty string.
        assert_eq!(
            build_response("q1", &respond_args()),
            InteractionResponse::text("q1", "")
        );
    }

    #[test]
    fn build_response_choice_selects_index() {
        let r = build_response(
            "q1",
            &RespondArgs {
                choice: Some(2),
                ..respond_args()
            },
        );
        assert_eq!(r, InteractionResponse::choice("q1", 2));
    }

    #[test]
    fn build_response_approve_and_deny_and_session_scope() {
        let approved = build_response(
            "q1",
            &RespondArgs {
                approve: true,
                ..respond_args()
            },
        );
        assert_eq!(
            approved,
            InteractionResponse::approval("q1", true, ApprovalScope::Once)
        );
        let session = build_response(
            "q1",
            &RespondArgs {
                approve: true,
                session: true,
                json: false,
                ..respond_args()
            },
        );
        assert_eq!(
            session,
            InteractionResponse::approval("q1", true, ApprovalScope::Run)
        );
        let stage = build_response(
            "q1",
            &RespondArgs {
                approve: true,
                stage: true,
                ..respond_args()
            },
        );
        assert_eq!(
            stage,
            InteractionResponse::approval("q1", true, ApprovalScope::Stage)
        );
        let denied = build_response(
            "q1",
            &RespondArgs {
                deny: true,
                ..respond_args()
            },
        );
        assert_eq!(
            denied,
            InteractionResponse::approval("q1", false, ApprovalScope::Once)
        );
    }

    #[test]
    fn kind_label_covers_every_kind() {
        for (kind, label) in [
            (InteractionKind::FreeText, "free-text"),
            (InteractionKind::MultipleChoice, "choice"),
            (InteractionKind::Confirm, "confirm"),
            (InteractionKind::ToolApproval, "tool-approval"),
            (InteractionKind::EditText, "edit-text"),
        ] {
            assert_eq!(kind_label(&kind), label);
        }
    }

    #[test]
    fn format_interaction_renders_options_and_tool() {
        let mut req = InteractionRequest::multiple_choice(
            "q1",
            "Pick",
            vec!["a".to_string(), "b".to_string()],
            "plan",
        );
        req.tool_name = Some("bash".to_string());
        let out = format_interaction("agent-x", &req);
        assert!(out.contains("q1  [choice]  agent=agent-x  stage=plan"));
        assert!(out.contains("Pick"));
        assert!(out.contains("0) a"));
        assert!(out.contains("1) b"));
        assert!(out.contains("tool: bash"));
    }

    #[tokio::test]
    async fn respond_answers_an_interaction() {
        let r = with_daemon(r#"{"result":"ok","ok":true}"#, |c| async move {
            respond(&c, &respond_args()).await
        })
        .await;
        assert!(r.is_ok());
    }

    #[tokio::test]
    async fn respond_reports_no_open_interaction() {
        let r = with_daemon(r#"{"result":"ok","ok":false}"#, |c| async move {
            respond(&c, &respond_args()).await
        })
        .await;
        assert!(r.unwrap_err().to_string().contains("no such open"));
    }

    // ─── --json ──────────────────────────────────────────────────────────

    #[test]
    fn open_interaction_serializes_the_agent_id_alongside_the_request() {
        // `#[serde(flatten)]` is what puts `id` and `prompt` at the top level
        // next to `agent_id`. Losing it would nest the request under a key no
        // caller expects.
        let mut request = InteractionRequest::multiple_choice(
            "q1",
            "Pick",
            vec!["a".to_string(), "b".to_string()],
            "plan",
        );
        request.tool_name = Some("bash".to_string());
        let open = OpenInteraction {
            agent_id: "agent-x",
            request: &request,
        };
        let value: serde_json::Value =
            serde_json::from_str(&serde_json::to_string(&open).unwrap()).unwrap();
        assert_eq!(value["agent_id"], serde_json::json!("agent-x"));
        assert_eq!(value["id"], serde_json::json!("q1"));
        assert_eq!(value["stage_name"], serde_json::json!("plan"));
        assert_eq!(value["options"], serde_json::json!(["a", "b"]));
        assert_eq!(value["tool_name"], serde_json::json!("bash"));
    }

    #[tokio::test]
    async fn respond_lists_open_interactions_as_json() {
        let req = InteractionRequest::free_text("q1", "What now?", "plan", true);
        let line = serde_json::to_string(&ControlResponse::Interactions {
            interactions: vec![("agent-a".to_string(), req)],
        })
        .unwrap();
        let r = with_daemon(line, |c| async move {
            respond(
                &c,
                &RespondArgs {
                    request_id: None,
                    json: true,
                    ..respond_args()
                },
            )
            .await
        })
        .await;
        assert!(r.is_ok());
    }

    #[tokio::test]
    async fn respond_lists_nothing_open_as_json() {
        let line = serde_json::to_string(&ControlResponse::Interactions {
            interactions: Vec::new(),
        })
        .unwrap();
        let r = with_daemon(line, |c| async move {
            respond(
                &c,
                &RespondArgs {
                    request_id: None,
                    json: true,
                    ..respond_args()
                },
            )
            .await
        })
        .await;
        assert!(r.is_ok());
    }

    #[tokio::test]
    async fn respond_answers_an_interaction_as_json() {
        let r = with_daemon(r#"{"result":"ok","ok":true}"#, |c| async move {
            respond(
                &c,
                &RespondArgs {
                    json: true,
                    ..respond_args()
                },
            )
            .await
        })
        .await;
        assert!(r.is_ok());
    }

    #[tokio::test]
    async fn respond_lists_open_interactions() {
        let req = InteractionRequest::free_text("q1", "What now?", "plan", true);
        let line = serde_json::to_string(&ControlResponse::Interactions {
            interactions: vec![("agent-a".to_string(), req)],
        })
        .unwrap();
        let r = with_daemon(line, |c| async move {
            respond(
                &c,
                &RespondArgs {
                    request_id: None,
                    ..respond_args()
                },
            )
            .await
        })
        .await;
        assert!(r.is_ok());
    }

    #[tokio::test]
    async fn respond_lists_when_none_open() {
        let line = serde_json::to_string(&ControlResponse::Interactions {
            interactions: vec![],
        })
        .unwrap();
        let r = with_daemon(line, |c| async move {
            respond(
                &c,
                &RespondArgs {
                    request_id: None,
                    ..respond_args()
                },
            )
            .await
        })
        .await;
        assert!(r.is_ok());
    }

    #[tokio::test]
    async fn respond_list_rejects_unexpected_response() {
        let r = with_daemon(r#"{"result":"ok","ok":true}"#, |c| async move {
            respond(
                &c,
                &RespondArgs {
                    request_id: None,
                    ..respond_args()
                },
            )
            .await
        })
        .await;
        assert!(r.unwrap_err().to_string().contains("unexpected"));
    }

    #[tokio::test]
    async fn respond_list_errors_when_daemon_absent() {
        let dir = tempfile::tempdir().unwrap();
        let client = ControlClient::new(control_id(&dir.path().join("no-daemon")));
        let err = respond(
            &client,
            &RespondArgs {
                request_id: None,
                ..respond_args()
            },
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("not reachable"));
    }
}