ag-agent 0.22.1

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
//! Stdio JSON-RPC transport helper unit tests for responses, errors, and
//! child shutdown.

use std::os::unix::process::CommandExt as _;
use std::process::Stdio;
use std::time::Duration;

use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};

use crate::app_server::AppServerError;
use crate::app_server_transport::{
    AppServerRuntimeChild, AppServerTransportError, extract_json_error_message,
    response_id_matches, shutdown_child, spawn_runtime_command, take_runtime_stdio,
    wait_for_response_line, wait_for_response_line_with_timeout, write_json_line,
};

/// Spawns a simple echo process that mirrors stdin to stdout for transport
/// write tests.
fn spawn_cat_process() -> (
    AppServerRuntimeChild,
    tokio::process::ChildStdin,
    tokio::process::ChildStdout,
) {
    let command = std::process::Command::new("cat");

    spawn_runtime_command(command, "cat").expect("failed to spawn `cat`")
}

#[test]
fn response_id_matches_returns_true_for_matching_string_id() {
    // Arrange
    let response_value = serde_json::json!({"id": "init-123", "result": {}});

    // Act / Assert
    assert!(response_id_matches(&response_value, "init-123"));
}

#[tokio::test]
async fn runtime_disables_optional_git_locks_for_tools() {
    // Arrange
    let mut command = std::process::Command::new("sh");
    command
        .args(["-c", "sh -c 'printf \"%s\\n\" \"$GIT_OPTIONAL_LOCKS\"'"])
        .env("GIT_OPTIONAL_LOCKS", "1");

    // Act
    let (mut child, stdin, stdout) =
        spawn_runtime_command(command, "test").expect("runtime should start");
    drop(stdin);
    let line = BufReader::new(stdout)
        .lines()
        .next_line()
        .await
        .expect("stdout should be readable");
    shutdown_child(&mut child).await;

    // Assert
    assert_eq!(line.as_deref(), Some("0"));
}

#[test]
fn response_id_matches_returns_false_for_different_id() {
    // Arrange
    let response_value = serde_json::json!({"id": "init-123", "result": {}});

    // Act / Assert
    assert!(!response_id_matches(&response_value, "init-456"));
}

#[test]
fn response_id_matches_returns_false_when_id_is_missing() {
    // Arrange
    let response_value = serde_json::json!({"method": "session/update", "params": {}});

    // Act / Assert
    assert!(!response_id_matches(&response_value, "init-123"));
}

#[test]
fn response_id_matches_returns_false_for_integer_id() {
    // Arrange
    let response_value = serde_json::json!({"id": 1, "result": {}});

    // Act / Assert
    assert!(!response_id_matches(&response_value, "1"));
}

#[test]
fn extract_json_error_message_returns_message_string() {
    // Arrange
    let response_value = serde_json::json!({
        "id": "req-1",
        "error": {"code": -32600, "message": "Invalid request"}
    });

    // Act
    let message = extract_json_error_message(&response_value);

    // Assert
    assert_eq!(message, Some("Invalid request".to_string()));
}

#[test]
fn extract_json_error_message_returns_none_without_error() {
    // Arrange
    let response_value = serde_json::json!({"id": "req-1", "result": {}});

    // Act
    let message = extract_json_error_message(&response_value);

    // Assert
    assert_eq!(message, None);
}

#[test]
fn extract_json_error_message_returns_none_without_message_field() {
    // Arrange
    let response_value = serde_json::json!({
        "id": "req-1",
        "error": {"code": -32600}
    });

    // Act
    let message = extract_json_error_message(&response_value);

    // Assert
    assert_eq!(message, None);
}

/// Verifies `write_json_line()` serializes one compact JSON line followed
/// by a newline.
#[tokio::test]
async fn write_json_line_writes_serialized_payload_with_newline() {
    // Arrange
    let (mut child, mut stdin, stdout) = spawn_cat_process();
    let payload = serde_json::json!({
        "id": "req-1",
        "method": "initialize",
        "params": {"value": 1}
    });

    // Act
    write_json_line(&mut stdin, &payload)
        .await
        .expect("write should succeed");
    drop(stdin);
    let echoed_line = BufReader::new(stdout)
        .lines()
        .next_line()
        .await
        .expect("stdout read should succeed")
        .expect("echoed payload line should exist");

    // Assert
    assert_eq!(echoed_line, payload.to_string());
    shutdown_child(&mut child).await;
}

/// Verifies `write_json_line()` reports a broken pipe once the runtime has
/// exited and no reader remains for its stdin.
#[tokio::test]
async fn write_json_line_reports_write_failure_after_runtime_exit() {
    // Arrange
    let (mut child, mut stdin, _stdout) =
        spawn_runtime_command(std::process::Command::new("true"), "true")
            .expect("failed to spawn `true`");
    child
        .child
        .wait()
        .await
        .expect("exited runtime should be reaped");

    // Act
    let result = write_json_line(&mut stdin, &serde_json::json!({"id": "req-1"})).await;

    // Assert
    assert!(
        matches!(
            &result,
            Err(AppServerTransportError::Io { context, source })
                if context == "Failed writing to app-server stdin"
                    && source.kind() == std::io::ErrorKind::BrokenPipe
        ),
        "unexpected write result: {result:?}"
    );
    shutdown_child(&mut child).await;
}

/// Verifies unreadable stdout surfaces as a contextual IO error instead of
/// being skipped like an unparsable JSON line.
#[tokio::test]
async fn wait_for_response_line_reports_stdout_read_failure() {
    // Arrange
    let mut stdout_lines = BufReader::new(&b"\xff\n"[..]).lines();

    // Act
    let response_result = wait_for_response_line(&mut stdout_lines, "req-1").await;

    // Assert
    assert!(
        matches!(
            &response_result,
            Err(AppServerTransportError::Io { context, source })
                if context == "Failed reading app-server stdout"
                    && source.kind() == std::io::ErrorKind::InvalidData
        ),
        "unexpected read result: {response_result:?}"
    );
}

/// Verifies runtime adoption rejects children whose stdin or stdout pipe was
/// not captured.
#[tokio::test]
async fn take_runtime_stdio_rejects_missing_pipes() {
    for (stdin, stdout, expected_message) in [
        (
            Stdio::null(),
            Stdio::piped(),
            "fixture stdin is unavailable",
        ),
        (
            Stdio::piped(),
            Stdio::null(),
            "fixture stdout is unavailable",
        ),
    ] {
        // Arrange
        let mut command = std::process::Command::new("cat");
        command.process_group(0);
        let child = tokio::process::Command::from(command)
            .stdin(stdin)
            .stdout(stdout)
            .stderr(Stdio::null())
            .kill_on_drop(true)
            .spawn()
            .expect("fixture should spawn");

        // Act
        let result = take_runtime_stdio(child, "fixture");

        // Assert
        assert!(
            matches!(&result, Err(AppServerError::Provider(message)) if message == expected_message),
            "unexpected adoption result for `{expected_message}`"
        );
    }
}

/// Verifies `wait_for_response_line()` skips unrelated or invalid lines
/// until the matching response id arrives.
#[tokio::test]
async fn wait_for_response_line_skips_invalid_and_non_matching_lines() {
    // Arrange
    let (reader, mut writer) = tokio::io::duplex(512);
    let writer_task = tokio::spawn(async move {
        writer
            .write_all(
                b"not-json\n{\"id\":\"other\",\"result\":{}}\n{\"id\":\"req-1\",\"result\":{\"ok\":true}}\n",
            )
            .await
            .expect("test writer should succeed");
    });
    let mut stdout_lines = BufReader::new(reader).lines();

    // Act
    let response_line = wait_for_response_line(&mut stdout_lines, "req-1")
        .await
        .expect("matching response should be returned");

    // Assert
    assert_eq!(response_line, "{\"id\":\"req-1\",\"result\":{\"ok\":true}}");
    writer_task.await.expect("writer task should finish");
}

/// Verifies `wait_for_response_line()` reports early process termination
/// when the stream ends before the expected response arrives.
#[tokio::test]
async fn wait_for_response_line_returns_error_when_stream_ends() {
    // Arrange
    let (reader, mut writer) = tokio::io::duplex(256);
    let writer_task = tokio::spawn(async move {
        writer
            .write_all(b"{\"id\":\"other\",\"result\":{}}\n")
            .await
            .expect("test writer should succeed");
        drop(writer);
    });
    let mut stdout_lines = BufReader::new(reader).lines();

    // Act
    let response_result = wait_for_response_line(&mut stdout_lines, "req-1").await;

    // Assert
    assert!(
        matches!(
            response_result,
            Err(AppServerTransportError::ProcessTerminated)
        ),
        "expected ProcessTerminated, got: {response_result:?}"
    );
    writer_task.await.expect("writer task should finish");
}

/// Verifies provider-selected response deadlines are preserved in timeout
/// diagnostics instead of falling back to the shared startup window.
#[tokio::test]
async fn wait_for_response_line_with_timeout_uses_selected_deadline() {
    // Arrange
    let (reader, _writer) = tokio::io::duplex(256);
    let mut stdout_lines = BufReader::new(reader).lines();
    let response_timeout = Duration::from_millis(1);

    // Act
    let response_result =
        wait_for_response_line_with_timeout(&mut stdout_lines, "req-1", response_timeout).await;

    // Assert
    assert!(matches!(
        response_result,
        Err(AppServerTransportError::Timeout {
            ref response_id,
            timeout_seconds: 0,
        }) if response_id == "req-1"
    ));
}

#[test]
fn io_error_display_includes_context_and_source() {
    // Arrange
    let error = AppServerTransportError::Io {
        context: "Failed writing to app-server stdin".to_string(),
        source: std::io::Error::new(std::io::ErrorKind::BrokenPipe, "pipe closed"),
    };

    // Act
    let display = error.to_string();

    // Assert
    assert_eq!(display, "Failed writing to app-server stdin: pipe closed");
}

#[test]
fn process_terminated_display_message() {
    // Arrange
    let error = AppServerTransportError::ProcessTerminated;

    // Act / Assert
    assert_eq!(
        error.to_string(),
        "App-server terminated before sending expected response"
    );
}

#[test]
fn timeout_display_includes_response_id_and_seconds() {
    // Arrange
    let error = AppServerTransportError::Timeout {
        response_id: "init-123".to_string(),
        timeout_seconds: 300,
    };

    // Act / Assert
    assert_eq!(
        error.to_string(),
        "Timed out waiting for app-server response `init-123` after 300 seconds"
    );
}

/// Verifies `shutdown_child()` closes stdin and reaps a cooperative child.
#[tokio::test]
async fn shutdown_child_reaps_process_after_closing_stdin() {
    // Arrange
    let (mut child, stdin, _stdout) = spawn_cat_process();

    // Act
    drop(stdin);
    shutdown_child(&mut child).await;

    // Assert
    assert!(child.id().is_none());
}

/// Verifies forced shutdown reaches descendants spawned by an app-server.
#[tokio::test]
async fn shutdown_child_terminates_runtime_process_group() {
    // Arrange
    let mut command = std::process::Command::new("sh");
    command.args([
        "-c",
        "trap '' TERM; sleep 60 & echo ready; cat >/dev/null; wait",
    ]);
    let (mut child, stdin, stdout) =
        spawn_runtime_command(command, "process-group fixture").expect("fixture should spawn");
    let mut stdout_lines = BufReader::new(stdout).lines();
    let readiness_line = stdout_lines
        .next_line()
        .await
        .expect("fixture readiness read should succeed")
        .expect("fixture readiness line should be present");
    assert_eq!(readiness_line, "ready");

    // Act
    drop(stdin);
    shutdown_child(&mut child).await;
    let stdout_closed =
        tokio::time::timeout(Duration::from_secs(2), stdout_lines.next_line()).await;

    // Assert
    assert!(
        matches!(stdout_closed, Ok(Ok(None))),
        "runtime descendant should release inherited stdout when its process group terminates"
    );
}