ag-agent 0.20.0

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
//! One-shot protocol repair and invalid utility output unit tests.

use std::process::Command;
use std::sync::{Arc, Mutex};

use ag_contracts::{AgentRequestKind, OneShotRequest, PermissionMode, ReasoningLevel, SpeedMode};
use ag_protocol::TurnPromptAttachment;
use ag_session::{AgentKind, AgentModel, test_support as model_fixture};
use tempfile::tempdir;

use super::support::mock_shell_command;
use crate::agent::MockAgentBackend;
use crate::agent::submission::{attempt_one_shot_app_server_repair, submit_one_shot_with_backend};
use crate::app_server::MockAppServerClient;

#[tokio::test]
async fn oversized_one_shot_responses_do_not_launch_repair() {
    // Arrange
    let folder = tempdir().expect("workspace");
    let oversized = "x".repeat(128 * 1024 + 1);
    let response_path = folder.path().join("response.txt");
    std::fs::write(&response_path, &oversized).expect("response fixture");
    let mut backend = MockAgentBackend::new();
    backend.expect_build_command().times(1).returning(move |_| {
        let mut command = Command::new("cat");
        command.arg(&response_path);

        Ok(command)
    });
    let client = MockAppServerClient::new();
    let request = OneShotRequest {
        activity_tx: None,
        attachments: Vec::new(),
        execution_policy: ag_contracts::ExecutionPolicy::default(),
        provider_call_budget: None,
        harness: (AgentKind::Claude).to_string(),
        child_pid: None,
        folder: folder.path().to_owned(),
        model: AgentModel::ClaudeSonnet55.as_str().to_string(),
        permission_mode: PermissionMode::AutoEdit,
        prompt: "Generate title".into(),
        request_kind: AgentRequestKind::UtilityPrompt,
        reasoning_level: ReasoningLevel::default(),
        speed_mode: SpeedMode::Normal,
    };

    // Act
    let cli_error = submit_one_shot_with_backend(&backend, request.clone())
        .await
        .expect_err("oversized CLI response");
    let native_error = attempt_one_shot_app_server_repair(
        &client,
        "bad JSON",
        &oversized,
        request,
        "repair-limit",
        None,
        false,
    )
    .await
    .expect_err("oversized native response");

    // Assert
    assert!(cli_error.contains("lossless repair limit"));
    assert!(native_error.contains("lossless repair limit"));
}

#[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_eq!(
                request.execution_policy.max_concurrent_subagents,
                std::num::NonZeroUsize::new(7)
            );
            assert!(matches!(
                request.request_kind,
                AgentRequestKind::UtilityPrompt
            ));

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

    // Act
    let error = submit_one_shot_with_backend(
        &backend,
        OneShotRequest {
            activity_tx: None,
            attachments: Vec::new(),
            execution_policy: ag_contracts::ExecutionPolicy {
                max_concurrent_subagents: std::num::NonZeroUsize::new(7),
                ..ag_contracts::ExecutionPolicy::default()
            },
            provider_call_budget: None,
            harness: (AgentKind::Codex).to_string(),
            child_pid: None,
            folder: temp_directory.path().to_path_buf(),
            model: model_fixture::CODEX_MODEL.as_str().to_string(),
            permission_mode: PermissionMode::AutoEdit,
            prompt: "Generate title".to_string(),
            request_kind: AgentRequestKind::UtilityPrompt,
            reasoning_level: ReasoningLevel::default(),
            speed_mode: SpeedMode::Normal,
        },
    )
    .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 {
            activity_tx: None,
            attachments: Vec::new(),
            execution_policy: ag_contracts::ExecutionPolicy::default(),
            provider_call_budget: None,
            harness: (AgentKind::Claude).to_string(),
            child_pid: None,
            folder: temp_directory.path().to_path_buf(),
            model: AgentModel::ClaudeSonnet55.as_str().to_string(),
            permission_mode: PermissionMode::AutoEdit,
            prompt: "Generate title".to_string(),
            request_kind: AgentRequestKind::UtilityPrompt,
            reasoning_level: ReasoningLevel::default(),
            speed_mode: SpeedMode::Normal,
        },
    )
    .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"}"#
                ),
                "",
                0,
            ))
        });

    // Act
    let response = submit_one_shot_with_backend(
        &backend,
        OneShotRequest {
            activity_tx: None,
            attachments: Vec::new(),
            execution_policy: ag_contracts::ExecutionPolicy::default(),
            provider_call_budget: None,
            harness: (AgentKind::Claude).to_string(),
            child_pid: None,
            folder: temp_directory.path().to_path_buf(),
            model: AgentModel::ClaudeSonnet55.as_str().to_string(),
            permission_mode: PermissionMode::AutoEdit,
            prompt: "Generate title".to_string(),
            request_kind: AgentRequestKind::UtilityPrompt,
            reasoning_level: ReasoningLevel::default(),
            speed_mode: SpeedMode::Normal,
        },
    )
    .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 |request| {
            assert_eq!(request.speed_mode, SpeedMode::Fast);
            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"}"#, "", 0))
            }
        }
    });

    // Act
    let response = submit_one_shot_with_backend(
        &backend,
        OneShotRequest {
            activity_tx: None,
            attachments: Vec::new(),
            execution_policy: ag_contracts::ExecutionPolicy::default(),
            provider_call_budget: None,
            harness: (AgentKind::Codex).to_string(),
            child_pid: None,
            folder: temp_directory.path().to_path_buf(),
            model: model_fixture::CODEX_MODEL.as_str().to_string(),
            permission_mode: PermissionMode::AutoEdit,
            prompt: "Generate title".to_string(),
            request_kind: AgentRequestKind::UtilityPrompt,
            reasoning_level: ReasoningLevel::default(),
            speed_mode: SpeedMode::Fast,
        },
    )
    .await
    .expect("repair retry should succeed");

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

#[tokio::test]
async fn focused_review_repairs_trailing_text_with_direct_review_schema() {
    // Arrange
    let temp_directory = tempdir().expect("failed to create temp dir");
    let call_counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let mut backend = MockAgentBackend::new();
    backend.expect_build_command().times(2).returning({
        let counter = Arc::clone(&call_counter);

        move |request| {
            assert_eq!(request.request_kind, &AgentRequestKind::FocusedReview);
            let call_number = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);

            if call_number == 0 {
                return Ok(mock_shell_command(
                    r#"{"project_impact":[],"suggestions":[]} trailing text"#,
                    "",
                    0,
                ));
            }

            assert!(request.prompt.contains("Complete malformed response:"));
            let prompt = crate::agent::prompt::build_cli_prompt_text(
                request,
                ag_protocol::ProtocolSchemaInstructionMode::PromptSchema,
                "Claude",
            )
            .expect("repair envelope");
            assert!(prompt.contains("\"title\": \"FocusedReview\""));
            assert_eq!(prompt.matches("Authoritative JSON Schema:").count(), 1);
            assert!(!prompt.contains("\"answer\""));

            Ok(mock_shell_command(
                r#"{"project_impact":["Review repaired."],"suggestions":[]}"#,
                "",
                0,
            ))
        }
    });

    // Act
    let response = submit_one_shot_with_backend(
        &backend,
        OneShotRequest {
            activity_tx: None,
            attachments: Vec::new(),
            execution_policy: ag_contracts::ExecutionPolicy::default(),
            provider_call_budget: None,
            harness: (AgentKind::Claude).to_string(),
            child_pid: None,
            folder: temp_directory.path().to_path_buf(),
            model: AgentModel::ClaudeSonnet55.as_str().to_string(),
            permission_mode: PermissionMode::ReadOnly,
            prompt: "Review the diff".to_string(),
            request_kind: AgentRequestKind::FocusedReview,
            reasoning_level: ReasoningLevel::default(),
            speed_mode: SpeedMode::Normal,
        },
    )
    .await
    .expect("focused review repair should succeed");

    // Assert
    assert_eq!(
        response.response.answer,
        r#"{"project_impact":["Review repaired."],"suggestions":[]}"#
    );
}

#[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 {
            activity_tx: None,
            attachments: Vec::new(),
            execution_policy: ag_contracts::ExecutionPolicy::default(),
            provider_call_budget: None,
            harness: (AgentKind::Codex).to_string(),
            child_pid: None,
            folder: temp_directory.path().to_path_buf(),
            model: model_fixture::CODEX_MODEL.as_str().to_string(),
            permission_mode: PermissionMode::AutoEdit,
            prompt: "Generate title".to_string(),
            request_kind: AgentRequestKind::UtilityPrompt,
            reasoning_level: ReasoningLevel::default(),
            speed_mode: SpeedMode::Normal,
        },
    )
    .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 CLI one-shot commands receive images on the initial attempt
/// only; the stateless protocol repair command stays text-only.
async fn test_submit_one_shot_with_backend_sends_images_only_initially() {
    // Arrange
    let temp_directory = tempdir().expect("failed to create temp dir");
    let attachment = TurnPromptAttachment {
        local_image_path: "design.png".into(),
        placeholder: "[Task image #1]".into(),
    };
    let seen = Arc::new(Mutex::new(Vec::new()));
    let recorded = Arc::clone(&seen);
    let mut backend = MockAgentBackend::new();
    backend
        .expect_build_command()
        .times(2)
        .returning(move |request| {
            recorded
                .lock()
                .expect("commands")
                .push(request.attachments.to_vec());

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

    // Act
    let error = submit_one_shot_with_backend(
        &backend,
        OneShotRequest {
            activity_tx: None,
            attachments: vec![attachment.clone()],
            execution_policy: ag_contracts::ExecutionPolicy::default(),
            provider_call_budget: None,
            harness: (AgentKind::Codex).to_string(),
            child_pid: None,
            folder: temp_directory.path().to_path_buf(),
            model: model_fixture::CODEX_MODEL.as_str().to_string(),
            permission_mode: PermissionMode::ReadOnly,
            prompt: "Describe [Task image #1]".to_string(),
            request_kind: AgentRequestKind::UtilityPrompt,
            reasoning_level: ReasoningLevel::default(),
            speed_mode: SpeedMode::Normal,
        },
    )
    .await
    .expect_err("plain-text utility output should fail");

    // Assert
    assert!(error.contains("repair retry also failed"));
    assert_eq!(
        *seen.lock().expect("commands"),
        [vec![attachment], Vec::new()]
    );
}