ag-agent 0.12.4

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
//! One-shot agent prompt execution helpers.
//!
//! These helpers run isolated utility prompts outside the long-lived session
//! turn flow. They require the shared structured response protocol on every
//! transport so one-shot callers enforce the same schema contract as normal
//! session turns.

use std::os::unix::process::ExitStatusExt as _;
use std::path::Path;
use std::sync::{Arc, Mutex};

use ag_protocol::{
    AgentResponse, build_protocol_repair_prompt, format_protocol_parse_debug_details,
    parse_agent_response_strict,
};

use super::backend::{AgentBackend, BuildCommandRequest};
use super::cli::{error, stdin};
use super::{
    ParsedResponse, create_app_server_client, create_backend, parse_response, transport_mode,
};
use crate::app_server::{AppServerClient, AppServerTurnRequest};
use crate::channel::AgentRequestKind;
use crate::model::agent::{AgentKind, AgentModel, ReasoningLevel};
use crate::model::session::SessionStats;

/// Input payload for one isolated prompt that prefers structured protocol
/// output.
#[derive(Clone, Debug)]
pub struct OneShotRequest<'a> {
    /// Provider backend used for command construction, stdin shaping, and
    /// response parsing.
    pub agent_kind: AgentKind,
    /// Optional PID slot used by cancel/stop flows to terminate the spawned
    /// subprocess while a one-shot prompt is running.
    pub child_pid: Option<&'a Mutex<Option<u32>>>,
    /// Working directory where the prompt command runs.
    pub folder: &'a Path,
    /// Provider-specific model used for command construction and parsing.
    pub model: AgentModel,
    /// Prompt text submitted to the agent.
    pub prompt: &'a str,
    /// Canonical request kind for this isolated prompt.
    pub request_kind: AgentRequestKind,
    /// Reasoning effort preference for the one-shot prompt.
    pub reasoning_level: ReasoningLevel,
}

/// Parsed result returned by one isolated prompt execution.
#[derive(Clone, Debug, PartialEq)]
pub struct OneShotSubmission {
    /// Structured protocol response parsed from the final successful attempt.
    pub response: AgentResponse,
    /// Aggregated token usage for the one-shot prompt execution.
    pub stats: SessionStats,
}

/// Executes one isolated prompt and returns the parsed response.
///
/// # Errors
/// Returns an error when command construction fails, process execution fails,
/// or the final output is empty or otherwise unusable.
pub async fn submit_one_shot(request: OneShotRequest<'_>) -> Result<AgentResponse, String> {
    let submission = submit_one_shot_with_stats(request).await?;

    Ok(submission.response)
}

/// Executes one isolated prompt and returns the parsed response plus
/// aggregated usage statistics.
///
/// # Errors
/// Returns an error when command construction fails, process execution fails,
/// or the final output is empty or otherwise unusable.
pub(crate) async fn submit_one_shot_with_stats(
    request: OneShotRequest<'_>,
) -> Result<OneShotSubmission, String> {
    submit_one_shot_with_stats_and_app_server_client(request, None).await
}

/// Executes one isolated prompt and returns the parsed response plus
/// aggregated usage statistics, optionally overriding the backend-owned
/// app-server client.
///
/// # Errors
/// Returns an error when command construction fails, process execution fails,
/// or the final output is empty or otherwise unusable.
pub(crate) async fn submit_one_shot_with_stats_and_app_server_client(
    request: OneShotRequest<'_>,
    app_server_client_override: Option<Arc<dyn AppServerClient>>,
) -> Result<OneShotSubmission, String> {
    let backend = create_backend(request.agent_kind);

    if transport_mode(request.agent_kind).uses_app_server() {
        let app_server_client =
            create_app_server_client(request.agent_kind, app_server_client_override).ok_or_else(
                || {
                    format!(
                        "{} provider did not provide an app-server client",
                        request.agent_kind
                    )
                },
            )?;

        return submit_one_shot_with_app_server_client(app_server_client.as_ref(), request).await;
    }

    submit_one_shot_with_backend(backend.as_ref(), request).await
}

/// Executes one isolated prompt through the shared app-server transport.
///
/// The temporary app-server session is shut down after the utility prompt
/// finishes so one-shot helpers do not keep a provider runtime alive after the
/// result has been parsed.
///
/// # Errors
/// Returns an error when app-server turn execution fails or the final output
/// is empty or otherwise unusable.
pub async fn submit_one_shot_with_app_server_client(
    app_server_client: &dyn AppServerClient,
    request: OneShotRequest<'_>,
) -> Result<OneShotSubmission, String> {
    clear_child_pid_slot(request.child_pid);

    let session_id = format!("one-shot-{}", uuid::Uuid::new_v4());
    let (stream_tx, _stream_rx) = tokio::sync::mpsc::unbounded_channel();
    let turn_request = AppServerTurnRequest {
        folder: request.folder.to_path_buf(),
        live_transcript: None,
        main_checkout_root: None,
        model: request.model.provider_model_str().to_string(),
        prompt: crate::model::turn_prompt::TurnPrompt::from_agent_data(request.prompt.to_string()),
        request_kind: request.request_kind.clone(),
        replay_transcript: None,
        provider_conversation_id: None,
        persisted_instruction_conversation_id: None,
        reasoning_level: request.reasoning_level,
        session_id: session_id.clone(),
    };

    let turn_result = app_server_client.run_turn(turn_request, stream_tx).await;

    let child_pid = request.child_pid;

    let turn_result = match turn_result {
        Ok(result) => result,
        Err(error) => {
            app_server_client.shutdown_session(session_id).await;
            clear_child_pid_slot(child_pid);

            return Err(format!(
                "Failed to execute one-shot app-server turn: {error}"
            ));
        }
    };

    let parse_result = match parse_one_shot_response(&turn_result.assistant_message) {
        Ok(response) => Ok((response, 0, 0)),
        Err(parse_error) => {
            attempt_one_shot_app_server_repair(
                app_server_client,
                &parse_error,
                &turn_result.assistant_message,
                request,
                &session_id,
                turn_result.provider_conversation_id.as_deref(),
            )
            .await
        }
    };

    app_server_client.shutdown_session(session_id).await;
    clear_child_pid_slot(child_pid);

    let (response, repair_input_tokens, repair_output_tokens) = parse_result?;

    Ok(OneShotSubmission {
        response,
        stats: SessionStats {
            added_lines: 0,
            deleted_lines: 0,
            input_tokens: turn_result.input_tokens + repair_input_tokens,
            output_tokens: turn_result.output_tokens + repair_output_tokens,
        },
    })
}

/// Executes one isolated prompt using the provided backend.
///
/// This shared helper keeps process execution behind the existing
/// `AgentBackend` trait boundary so production callers and tests can reuse
/// the same one-shot parsing path.
///
/// # Errors
/// Returns an error when command construction fails, process execution fails,
/// or the final output is empty or otherwise unusable.
pub async fn submit_one_shot_with_backend(
    backend: &dyn AgentBackend,
    request: OneShotRequest<'_>,
) -> Result<OneShotSubmission, String> {
    let parsed_response =
        execute_one_shot_command(backend, request.prompt, request.clone()).await?;
    let (agent_response, repair_stats) = match parse_one_shot_response(&parsed_response.content) {
        Ok(response) => (response, None),
        Err(parse_error) => {
            let repair_prompt =
                build_protocol_repair_prompt(&parse_error, &parsed_response.content);
            let repair_response = execute_one_shot_command(backend, &repair_prompt, request)
                .await
                .map_err(|error| format!("{parse_error}\nrepair transport failed: {error}"))?;

            let response = parse_one_shot_response(&repair_response.content).map_err(|error| {
                format!(
                    "{parse_error}\nrepair retry also failed: {error}\nrepair_response:\n{}",
                    repair_response.content
                )
            })?;

            (response, Some(repair_response.stats))
        }
    };

    let mut stats = parsed_response.stats;
    if let Some(repair) = repair_stats {
        stats.input_tokens += repair.input_tokens;
        stats.output_tokens += repair.output_tokens;
    }

    Ok(OneShotSubmission {
        response: agent_response,
        stats,
    })
}

/// Parses one one-shot response strictly against the shared protocol schema.
///
/// # Errors
/// Returns an error when the response is empty or not valid protocol JSON,
/// including parse diagnostics that help explain the mismatch.
fn parse_one_shot_response(content: &str) -> Result<AgentResponse, String> {
    parse_agent_response_strict(content).map_err(|error| {
        format!(
            "One-shot agent output did not match the required JSON schema: \
             {error}\ndebug_details:\n{}\nresponse:\n{content}",
            format_protocol_parse_debug_details(content)
        )
    })
}

/// Attempts one protocol-repair retry through the app-server transport for
/// a one-shot prompt whose initial response failed schema validation.
///
/// The repair prompt is sent as a follow-up turn on the same session so the
/// agent retains the original conversation context. The initial turn's
/// `provider_conversation_id` is threaded through so providers that depend
/// on conversation state can continue the same thread.
///
/// Returns the parsed response together with the repair turn's token usage
/// so the caller can aggregate stats across both attempts.
///
/// # Errors
/// Returns the combined original and repair error when the retry fails.
async fn attempt_one_shot_app_server_repair(
    app_server_client: &dyn AppServerClient,
    parse_error: &str,
    malformed_response: &str,
    request: OneShotRequest<'_>,
    session_id: &str,
    provider_conversation_id: Option<&str>,
) -> Result<(AgentResponse, u64, u64), String> {
    let repair_prompt = build_protocol_repair_prompt(parse_error, malformed_response);

    let (repair_stream_tx, _repair_stream_rx) = tokio::sync::mpsc::unbounded_channel();
    let repair_turn_request = AppServerTurnRequest {
        folder: request.folder.to_path_buf(),
        live_transcript: None,
        main_checkout_root: None,
        model: request.model.provider_model_str().to_string(),
        prompt: crate::model::turn_prompt::TurnPrompt::from_agent_data(repair_prompt),
        request_kind: request.request_kind,
        replay_transcript: None,
        provider_conversation_id: provider_conversation_id.map(String::from),
        persisted_instruction_conversation_id: None,
        reasoning_level: request.reasoning_level,
        session_id: session_id.to_string(),
    };
    let repair_result = app_server_client
        .run_turn(repair_turn_request, repair_stream_tx)
        .await
        .map_err(|error| format!("{parse_error}\nrepair transport failed: {error}"))?;

    let response = parse_one_shot_response(&repair_result.assistant_message).map_err(|error| {
        format!(
            "{parse_error}\nrepair retry also failed: {error}\nrepair_response:\n{}",
            repair_result.assistant_message
        )
    })?;

    Ok((
        response,
        repair_result.input_tokens,
        repair_result.output_tokens,
    ))
}

/// Runs one one-shot backend command and returns the parsed provider content.
///
/// The spawned child is configured with `kill_on_drop(true)` so timeout-driven
/// callers do not leave orphaned agent CLI processes behind when the future is
/// canceled before completion.
///
/// # Errors
/// Returns an error when the command cannot be built, run, or exits
/// unsuccessfully.
async fn execute_one_shot_command(
    backend: &dyn AgentBackend,
    prompt: &str,
    request: OneShotRequest<'_>,
) -> Result<ParsedResponse, String> {
    let prompt_payload = crate::model::turn_prompt::TurnPrompt::from_agent_data(prompt.to_string());
    let build_request = BuildCommandRequest {
        attachments: &prompt_payload.attachments,
        folder: request.folder,
        main_checkout_root: None,
        replay_transcript: None,
        model: request.model.provider_model_str(),
        prompt,
        reasoning_level: request.reasoning_level,
        request_kind: &request.request_kind,
    };
    let command = backend
        .build_command(build_request)
        .map_err(|error| format!("Failed to build one-shot agent command: {error}"))?;
    let stdin_payload = super::build_command_stdin_payload(request.agent_kind, build_request)
        .map_err(|error| format!("Failed to build one-shot agent stdin payload: {error}"))?;
    let mut tokio_command = tokio::process::Command::from(command);
    tokio_command
        .stdin(if stdin_payload.is_some() {
            std::process::Stdio::piped()
        } else {
            std::process::Stdio::null()
        })
        .kill_on_drop(true);
    let mut pid_guard = ChildPidGuard::new(request.child_pid);
    let mut child = tokio_command
        .spawn()
        .map_err(|error| format!("Failed to execute one-shot agent command: {error}"))?;
    pid_guard.update_from_child(&child);
    let stdin_write_task = stdin::spawn_optional_stdin_write(
        child.stdin.take(),
        stdin_payload,
        "one-shot stdin pipe unavailable after spawn",
        std::convert::identity,
    );
    let output = child
        .wait_with_output()
        .await
        .map_err(|error| format!("Failed to execute one-shot agent command: {error}"))?;
    stdin::await_optional_stdin_write(
        stdin_write_task,
        "One-shot stdin write task failed",
        std::convert::identity,
    )
    .await?;

    if output.status.signal().is_some() {
        return Err("One-shot agent command was interrupted".to_string());
    }

    let stdout_text = String::from_utf8_lossy(&output.stdout).into_owned();
    let stderr_text = String::from_utf8_lossy(&output.stderr).into_owned();
    if !output.status.success() {
        return Err(format_one_shot_exit_error(
            request.agent_kind,
            output.status.code(),
            &stdout_text,
            &stderr_text,
        ));
    }

    let parsed_response = parse_response(request.agent_kind, &stdout_text, &stderr_text);

    Ok(parsed_response)
}

/// Formats one non-zero one-shot command exit into a user-facing error.
fn format_one_shot_exit_error(
    agent_kind: AgentKind,
    exit_code: Option<i32>,
    stdout: &str,
    stderr: &str,
) -> String {
    error::format_agent_cli_exit_error(
        agent_kind,
        "One-shot agent command",
        exit_code,
        stdout,
        stderr,
    )
}

/// Clears the shared one-shot child PID slot when one exists.
fn clear_child_pid_slot(child_pid: Option<&Mutex<Option<u32>>>) {
    let Some(child_pid) = child_pid else {
        return;
    };

    if let Ok(mut guard) = child_pid.lock() {
        *guard = None;
    }
}

/// Tracks the active one-shot subprocess identifier for cancel/stop flows.
struct ChildPidGuard<'a> {
    child_pid: Option<&'a Mutex<Option<u32>>>,
}

impl<'a> ChildPidGuard<'a> {
    /// Creates one PID guard for the optional shared child slot.
    fn new(child_pid: Option<&'a Mutex<Option<u32>>>) -> Self {
        Self { child_pid }
    }

    /// Copies the spawned child PID into the shared slot when available.
    fn update_from_child(&mut self, child: &tokio::process::Child) {
        let Some(pid) = child.id() else {
            return;
        };

        let Some(child_pid) = self.child_pid else {
            return;
        };

        if let Ok(mut guard) = child_pid.lock() {
            *guard = Some(pid);
        }
    }
}

impl Drop for ChildPidGuard<'_> {
    fn drop(&mut self) {
        let Some(child_pid) = self.child_pid else {
            return;
        };

        if let Ok(mut guard) = child_pid.lock() {
            *guard = None;
        }
    }
}

#[cfg(test)]
mod tests {
    use std::process::Command;
    use std::time::Duration;

    use tempfile::tempdir;

    use super::*;
    use crate::agent::tests::MockAgentBackend;
    use crate::app_server::{AppServerTurnResponse, MockAppServerClient};

    /// Builds one shell command that emits controlled stdout/stderr and exits.
    fn mock_shell_command(stdout: &str, stderr: &str, exit_code: i32) -> Command {
        let mut command = Command::new("sh");
        command.arg("-c").arg(
            "printf '%s' \"$ONE_SHOT_STDOUT\"; printf '%s' \"$ONE_SHOT_STDERR\" >&2; exit \
             \"$ONE_SHOT_EXIT\"",
        );
        command.env("ONE_SHOT_STDOUT", stdout);
        command.env("ONE_SHOT_STDERR", stderr);
        command.env("ONE_SHOT_EXIT", exit_code.to_string());
        command.stdout(std::process::Stdio::piped());
        command.stderr(std::process::Stdio::piped());

        command
    }

    /// Builds one shell command that captures stdin before returning JSON.
    fn stdin_capture_shell_command(capture_path: &Path) -> Command {
        let mut command = Command::new("sh");
        command.arg("-c").arg(
            "cat > \"$ONE_SHOT_CAPTURE_PATH\"; printf '%s' \
             '{\"answer\":\"captured\",\"questions\":[],\"summary\":null}'",
        );
        command.env("ONE_SHOT_CAPTURE_PATH", capture_path);
        command.stdout(std::process::Stdio::piped());
        command.stderr(std::process::Stdio::piped());

        command
    }

    #[tokio::test]
    /// Verifies one-shot execution returns the parsed structured answer.
    async fn test_submit_one_shot_with_backend_returns_protocol_response() {
        // Arrange
        let temp_directory = tempdir().expect("failed to create temp dir");
        let mut backend = MockAgentBackend::new();
        backend.expect_build_command().returning(|request| {
            assert!(matches!(
                request.request_kind,
                AgentRequestKind::UtilityPrompt
            ));
            assert_eq!(request.prompt, "Generate title");

            Ok(mock_shell_command(
                r#"{"answer":"Generated title","questions":[],"summary":null}"#,
                "",
                0,
            ))
        });

        // Act
        let response = submit_one_shot_with_backend(
            &backend,
            OneShotRequest {
                agent_kind: AgentKind::Claude,
                child_pid: None,
                folder: temp_directory.path(),
                model: AgentModel::ClaudeSonnet5,
                prompt: "Generate title",
                request_kind: AgentRequestKind::UtilityPrompt,
                reasoning_level: ReasoningLevel::default(),
            },
        )
        .await
        .expect("one-shot prompt should succeed");

        // Assert
        assert_eq!(
            response.response.answers(),
            vec!["Generated title".to_string()]
        );
    }

    #[tokio::test]
    /// Verifies one-shot execution rejects plain-text utility output after
    /// both the original parse and the protocol-repair retry fail.
    async fn test_submit_one_shot_with_backend_rejects_plain_text_utility_output() {
        // Arrange
        let temp_directory = tempdir().expect("failed to create temp dir");
        let mut backend = MockAgentBackend::new();
        backend
            .expect_build_command()
            .times(2)
            .returning(|request| {
                assert!(matches!(
                    request.request_kind,
                    AgentRequestKind::UtilityPrompt
                ));

                Ok(mock_shell_command("plain text", "", 0))
            });

        // Act
        let error = submit_one_shot_with_backend(
            &backend,
            OneShotRequest {
                agent_kind: AgentKind::Codex,
                child_pid: None,
                folder: temp_directory.path(),
                model: AgentModel::Gpt55,
                prompt: "Generate title",
                request_kind: AgentRequestKind::UtilityPrompt,
                reasoning_level: ReasoningLevel::default(),
            },
        )
        .await
        .expect_err("plain-text utility output should fail");

        // Assert
        assert!(error.contains("did not match the required JSON schema"));
        assert!(error.contains("debug_details:"));
        assert!(error.contains("direct_json_error_location: line 1, column 1"));
        assert!(error.contains("response:\nplain text"));
    }

    #[tokio::test]
    /// Verifies one-shot execution rejects wrapped non-schema utility output
    /// after both the original parse and the protocol-repair retry fail.
    async fn test_submit_one_shot_with_backend_rejects_wrapped_plain_text_utility_output() {
        // Arrange
        let temp_directory = tempdir().expect("failed to create temp dir");
        let mut backend = MockAgentBackend::new();
        backend
            .expect_build_command()
            .times(2)
            .returning(|request| {
                assert!(matches!(
                    request.request_kind,
                    AgentRequestKind::UtilityPrompt
                ));

                Ok(mock_shell_command(
                    r#"{"result":"plain text","usage":{"input_tokens":2,"output_tokens":1}}"#,
                    "",
                    0,
                ))
            });

        // Act
        let error = submit_one_shot_with_backend(
            &backend,
            OneShotRequest {
                agent_kind: AgentKind::Claude,
                child_pid: None,
                folder: temp_directory.path(),
                model: AgentModel::ClaudeSonnet5,
                prompt: "Generate title",
                request_kind: AgentRequestKind::UtilityPrompt,
                reasoning_level: ReasoningLevel::default(),
            },
        )
        .await
        .expect_err("wrapped plain-text utility output should fail");

        // Assert — the provider parser extracts "plain text" from the
        // `result` wrapper, so the protocol parser sees raw text, not JSON keys.
        assert!(error.contains("did not match the required JSON schema"));
        assert!(error.contains("direct_json_error:"));
        assert!(error.contains("response:\nplain text"));
    }

    #[tokio::test]
    /// Verifies one-shot execution recovers a trailing protocol payload when
    /// the provider prepends extra prose before the final JSON object.
    async fn test_submit_one_shot_with_backend_recovers_wrapped_protocol_output() {
        // Arrange
        let temp_directory = tempdir().expect("failed to create temp dir");
        let mut backend = MockAgentBackend::new();
        backend
            .expect_build_command()
            .times(1)
            .returning(|request| {
                assert!(matches!(
                    request.request_kind,
                    AgentRequestKind::UtilityPrompt
                ));
                assert_eq!(request.prompt, "Generate title");

                Ok(mock_shell_command(
                    concat!(
                        "Now I have full context.\n",
                        r#"{"answer":"Generated title","questions":[],"summary":null}"#
                    ),
                    "",
                    0,
                ))
            });

        // Act
        let response = submit_one_shot_with_backend(
            &backend,
            OneShotRequest {
                agent_kind: AgentKind::Claude,
                child_pid: None,
                folder: temp_directory.path(),
                model: AgentModel::ClaudeSonnet5,
                prompt: "Generate title",
                request_kind: AgentRequestKind::UtilityPrompt,
                reasoning_level: ReasoningLevel::default(),
            },
        )
        .await
        .expect("wrapped protocol output should succeed");

        // Assert
        assert_eq!(
            response.response.answers(),
            vec!["Generated title".to_string()]
        );
    }

    #[tokio::test]
    /// Verifies one-shot execution recovers valid output when the initial
    /// parse fails but the protocol-repair retry returns valid protocol JSON.
    async fn test_submit_one_shot_with_backend_recovers_via_protocol_repair() {
        // Arrange
        let temp_directory = tempdir().expect("failed to create temp dir");
        let call_counter = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let mut backend = MockAgentBackend::new();
        backend.expect_build_command().times(2).returning({
            let counter = std::sync::Arc::clone(&call_counter);

            move |_| {
                let call_number = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);

                if call_number == 0 {
                    Ok(mock_shell_command("plain text", "", 0))
                } else {
                    Ok(mock_shell_command(
                        r#"{"answer":"Repaired title","questions":[],"summary":null}"#,
                        "",
                        0,
                    ))
                }
            }
        });

        // Act
        let response = submit_one_shot_with_backend(
            &backend,
            OneShotRequest {
                agent_kind: AgentKind::Codex,
                child_pid: None,
                folder: temp_directory.path(),
                model: AgentModel::Gpt55,
                prompt: "Generate title",
                request_kind: AgentRequestKind::UtilityPrompt,
                reasoning_level: ReasoningLevel::default(),
            },
        )
        .await
        .expect("repair retry should succeed");

        // Assert
        assert_eq!(
            response.response.answers(),
            vec!["Repaired title".to_string()]
        );
    }

    #[tokio::test]
    /// Verifies one-shot execution still rejects blank utility responses
    /// after both the original parse and the protocol-repair retry fail.
    async fn test_submit_one_shot_with_backend_rejects_blank_utility_output() {
        // Arrange
        let temp_directory = tempdir().expect("failed to create temp dir");
        let mut backend = MockAgentBackend::new();
        backend.expect_build_command().returning(|request| {
            assert!(matches!(
                request.request_kind,
                AgentRequestKind::UtilityPrompt
            ));

            Ok(mock_shell_command("   ", "", 0))
        });

        // Act
        let error = submit_one_shot_with_backend(
            &backend,
            OneShotRequest {
                agent_kind: AgentKind::Codex,
                child_pid: None,
                folder: temp_directory.path(),
                model: AgentModel::Gpt55,
                prompt: "Generate title",
                request_kind: AgentRequestKind::UtilityPrompt,
                reasoning_level: ReasoningLevel::default(),
            },
        )
        .await
        .expect_err("blank utility output should fail");

        // Assert
        assert!(error.contains("did not match the required JSON schema"));
        assert!(error.contains("trimmed_len: 0 chars"));
        assert!(error.contains("response:\n"));
    }

    #[tokio::test]
    /// Verifies one-shot execution does not deadlock when the child delays
    /// reading stdin until after it emits early stderr output.
    async fn test_submit_one_shot_with_backend_writes_large_stdin_concurrently() {
        // Arrange
        let temp_directory = tempdir().expect("failed to create temp dir");
        let large_prompt = "x".repeat(512 * 1024);
        let mut backend = MockAgentBackend::new();
        backend.expect_build_command().returning(|_| {
            let mut command = Command::new("sh");
            command.arg("-c").arg(
                "printf 'warming up\\n' >&2; sleep 0.1; cat >/dev/null; printf '%s' \
                 '{\"answer\":\"done\",\"questions\":[],\"summary\":null}'",
            );
            command.stdout(std::process::Stdio::piped());
            command.stderr(std::process::Stdio::piped());

            Ok(command)
        });

        // Act
        let response = tokio::time::timeout(
            Duration::from_secs(5),
            submit_one_shot_with_backend(
                &backend,
                OneShotRequest {
                    agent_kind: AgentKind::Claude,
                    child_pid: None,
                    folder: temp_directory.path(),
                    model: AgentModel::ClaudeSonnet5,
                    prompt: &large_prompt,
                    request_kind: AgentRequestKind::UtilityPrompt,
                    reasoning_level: ReasoningLevel::default(),
                },
            ),
        )
        .await
        .expect("one-shot prompt should not deadlock")
        .expect("one-shot prompt should succeed");

        // Assert
        assert_eq!(response.response.answers(), vec!["done".to_string()]);
    }

    #[tokio::test]
    /// Verifies one-shot execution streams Claude prompts through stdin so
    /// large review requests avoid argv length limits.
    async fn test_submit_one_shot_with_backend_writes_prompt_to_stdin() {
        // Arrange
        let temp_directory = tempdir().expect("failed to create temp dir");
        let capture_path = temp_directory.path().join("stdin.txt");
        let mut backend = MockAgentBackend::new();
        backend.expect_build_command().returning({
            let capture_path = capture_path.clone();

            move |_| Ok(stdin_capture_shell_command(&capture_path))
        });

        // Act
        let response = submit_one_shot_with_backend(
            &backend,
            OneShotRequest {
                agent_kind: AgentKind::Claude,
                child_pid: None,
                folder: temp_directory.path(),
                model: AgentModel::ClaudeSonnet5,
                prompt: "Generate title",
                request_kind: AgentRequestKind::UtilityPrompt,
                reasoning_level: ReasoningLevel::default(),
            },
        )
        .await
        .expect("one-shot prompt should succeed");
        let captured_prompt =
            std::fs::read_to_string(&capture_path).expect("captured stdin payload should exist");

        // Assert
        assert_eq!(response.response.answers(), vec!["captured".to_string()]);
        assert!(captured_prompt.contains("Structured response protocol:"));
        assert!(captured_prompt.contains("Generate title"));
    }

    #[tokio::test]
    /// Verifies a broken stdin pipe does not hide the child exit status or
    /// stderr when the backend exits before reading the full prompt.
    async fn test_submit_one_shot_with_backend_preserves_exit_error_after_broken_pipe() {
        // Arrange
        let temp_directory = tempdir().expect("failed to create temp dir");
        let large_prompt = "x".repeat(512 * 1024);
        let mut backend = MockAgentBackend::new();
        backend.expect_build_command().returning(|_| {
            let mut command = Command::new("sh");
            command.arg("-c").arg("printf 'auth failed' >&2; exit 7");
            command.stdout(std::process::Stdio::piped());
            command.stderr(std::process::Stdio::piped());

            Ok(command)
        });

        // Act
        let error = submit_one_shot_with_backend(
            &backend,
            OneShotRequest {
                agent_kind: AgentKind::Claude,
                child_pid: None,
                folder: temp_directory.path(),
                model: AgentModel::ClaudeSonnet5,
                prompt: &large_prompt,
                request_kind: AgentRequestKind::UtilityPrompt,
                reasoning_level: ReasoningLevel::default(),
            },
        )
        .await
        .expect_err("one-shot prompt should surface the child exit");

        // Assert
        assert!(error.contains("exit code 7"), "error was: {error}");
        assert!(error.contains("auth failed"), "error was: {error}");
        assert!(
            !error.contains("stdin payload"),
            "stdin write error should not mask child failure: {error}"
        );
    }

    #[tokio::test]
    /// Verifies Claude authentication failures return actionable re-login
    /// guidance instead of raw transport output.
    async fn test_submit_one_shot_with_backend_surfaces_claude_auth_guidance() {
        // Arrange
        let temp_directory = tempdir().expect("failed to create temp dir");
        let mut backend = MockAgentBackend::new();
        backend.expect_build_command().returning(|_| {
            Ok(mock_shell_command(
                r#"{"type":"error","error":{"type":"authentication_error","message":"OAuth token has expired. Please obtain a new token or refresh your existing token."}}"#,
                "",
                1,
            ))
        });

        // Act
        let error = submit_one_shot_with_backend(
            &backend,
            OneShotRequest {
                agent_kind: AgentKind::Claude,
                child_pid: None,
                folder: temp_directory.path(),
                model: AgentModel::ClaudeSonnet5,
                prompt: "Generate title",
                request_kind: AgentRequestKind::UtilityPrompt,
                reasoning_level: ReasoningLevel::default(),
            },
        )
        .await
        .expect_err("expired Claude auth should fail");

        // Assert
        assert!(
            error.contains("One-shot agent command failed because Claude authentication expired")
        );
        assert!(error.contains("`claude auth login`"));
        assert!(error.contains("`claude auth status`"));
    }

    #[tokio::test]
    /// Verifies app-server-backed one-shot execution returns the parsed
    /// structured answer and usage totals.
    async fn test_submit_one_shot_with_app_server_client_returns_protocol_response() {
        // Arrange
        let temp_directory = tempdir().expect("failed to create temp dir");
        let mut app_server_client = MockAppServerClient::new();
        app_server_client
            .expect_run_turn()
            .times(1)
            .returning(|request, _| {
                assert_eq!(request.model, AgentModel::Gpt55.as_str());
                assert!(matches!(
                    request.request_kind,
                    AgentRequestKind::UtilityPrompt
                ));
                assert_eq!(request.prompt.text, "Generate title");

                Box::pin(async {
                    Ok(AppServerTurnResponse {
                        assistant_message:
                            r#"{"answer":"Generated title","questions":[],"summary":null}"#
                                .to_string(),
                        context_reset: false,
                        input_tokens: 11,
                        output_tokens: 7,
                        pid: Some(42),
                        provider_conversation_id: Some("thread-1".to_string()),
                    })
                })
            });
        app_server_client
            .expect_shutdown_session()
            .times(1)
            .returning(|_| Box::pin(async {}));

        // Act
        let response = submit_one_shot_with_app_server_client(
            &app_server_client,
            OneShotRequest {
                agent_kind: AgentKind::Codex,
                child_pid: None,
                folder: temp_directory.path(),
                model: AgentModel::Gpt55,
                prompt: "Generate title",
                request_kind: AgentRequestKind::UtilityPrompt,
                reasoning_level: ReasoningLevel::default(),
            },
        )
        .await
        .expect("one-shot prompt should succeed");

        // Assert
        assert_eq!(
            response.response.answers(),
            vec!["Generated title".to_string()]
        );
        assert_eq!(response.stats.input_tokens, 11);
        assert_eq!(response.stats.output_tokens, 7);
    }

    #[tokio::test]
    /// Verifies app-server-backed one-shot execution rejects plain-text
    /// utility output after both the original parse and the protocol-repair
    /// retry fail.
    async fn test_submit_one_shot_with_app_server_client_rejects_plain_text_utility_output() {
        // Arrange
        let temp_directory = tempdir().expect("failed to create temp dir");
        let mut app_server_client = MockAppServerClient::new();
        app_server_client
            .expect_run_turn()
            .times(2)
            .returning(|request, _| {
                assert_eq!(request.model, AgentModel::Gpt55.as_str());

                Box::pin(async {
                    Ok(AppServerTurnResponse {
                        assistant_message: "plain text".to_string(),
                        context_reset: false,
                        input_tokens: 2,
                        output_tokens: 1,
                        pid: None,
                        provider_conversation_id: None,
                    })
                })
            });
        app_server_client
            .expect_shutdown_session()
            .times(1)
            .returning(|_| Box::pin(async {}));

        // Act
        let error = submit_one_shot_with_app_server_client(
            &app_server_client,
            OneShotRequest {
                agent_kind: AgentKind::Codex,
                child_pid: None,
                folder: temp_directory.path(),
                model: AgentModel::Gpt55,
                prompt: "Generate title",
                request_kind: AgentRequestKind::UtilityPrompt,
                reasoning_level: ReasoningLevel::default(),
            },
        )
        .await
        .expect_err("plain-text utility output should fail");

        // Assert
        assert!(error.contains("did not match the required JSON schema"));
        assert!(error.contains("debug_details:"));
        assert!(error.contains("response:\nplain text"));
    }

    #[tokio::test]
    /// Verifies app-server-backed non-utility one-shot execution still
    /// rejects plain-text output after both the original parse and the
    /// protocol-repair retry fail.
    async fn test_submit_one_shot_with_app_server_client_rejects_plain_text_non_utility_output() {
        // Arrange
        let temp_directory = tempdir().expect("failed to create temp dir");
        let mut app_server_client = MockAppServerClient::new();
        app_server_client
            .expect_run_turn()
            .times(2)
            .returning(|request, _| {
                assert!(matches!(
                    request.request_kind,
                    AgentRequestKind::SessionStart
                ));

                Box::pin(async {
                    Ok(AppServerTurnResponse {
                        assistant_message: "plain text".to_string(),
                        context_reset: false,
                        input_tokens: 2,
                        output_tokens: 1,
                        pid: None,
                        provider_conversation_id: None,
                    })
                })
            });
        app_server_client
            .expect_shutdown_session()
            .times(1)
            .returning(|_| Box::pin(async {}));

        // Act
        let error = submit_one_shot_with_app_server_client(
            &app_server_client,
            OneShotRequest {
                agent_kind: AgentKind::Codex,
                child_pid: None,
                folder: temp_directory.path(),
                model: AgentModel::Gpt55,
                prompt: "Generate title",
                request_kind: AgentRequestKind::SessionStart,
                reasoning_level: ReasoningLevel::default(),
            },
        )
        .await
        .expect_err("invalid non-utility output should fail");

        // Assert
        assert!(error.contains("did not match the required JSON schema"));
        assert!(error.contains("debug_details:"));
        assert!(error.contains("response:\nplain text"));
    }
}