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
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
//! CLI channel turn execution tests covering spawning, stdin delivery, exit
//! and signal handling, error mapping, and progress forwarding.

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use ag_contracts::{
    AgentChannel, AgentDefinitionPrompt, AgentRequestKind, ReasoningLevel, TurnContinuation,
    TurnEvent, TurnRequest,
};
use ag_protocol::{TurnPrompt, TurnPromptAttachment, TurnPromptTextSource};
use ag_session::AgentKind;
use tempfile::{tempdir, tempdir_in};
use tokio::sync::mpsc;

use super::support::{make_turn_request, stdin_capture_command};
use crate::agent::cli::execution::{CliExecutionError, CliExecutionObserver, CliStdoutPayload};
use crate::agent::{MockAgentBackend, create_backend};
use crate::app_server::steering::TurnSteeringRegistry;
use crate::channel::cli::{
    CliAgentChannel, CliTurnObserver, build_command_request, map_cli_turn_execution_error,
};

/// Delivers one stdout line with the payload the shared executor parses.
fn observe_line(observer: &CliTurnObserver, line: &str) {
    observer.stdout_line(line, &CliStdoutPayload::parse(line));
}

/// Drains all currently buffered turn events from a test receiver.
#[test]
fn test_map_cli_turn_execution_error_preserves_error_categories() {
    // Arrange
    let command_error = CliExecutionError::CommandBuild(
        crate::agent::AgentBackendError::CommandBuild("command".to_string()),
    );
    let spawn_error = CliExecutionError::Spawn(std::io::Error::other("spawn unavailable"));
    let stdin_error = CliExecutionError::StdinBuild(crate::agent::AgentBackendError::CommandBuild(
        "stdin".to_string(),
    ));
    let io_error = CliExecutionError::StdinWrite("write unavailable".to_string());

    // Act
    let command_message = map_cli_turn_execution_error(command_error).to_string();
    let spawn_message = map_cli_turn_execution_error(spawn_error).to_string();
    let stdin_message = map_cli_turn_execution_error(stdin_error).to_string();
    let io_message = map_cli_turn_execution_error(io_error).to_string();

    // Assert
    assert_eq!(command_message, "Failed to build command: command");
    assert_eq!(spawn_message, "Failed to spawn process: spawn unavailable");
    assert_eq!(
        stdin_message,
        "Failed to build command stdin payload: stdin"
    );
    assert_eq!(io_message, "stdin delivery failed: write unavailable");
}

#[test]
fn test_cli_turn_observer_ignores_blank_progress_text() {
    // Arrange
    let (events, mut event_receiver) = mpsc::unbounded_channel();
    let observer = CliTurnObserver::new(events, AgentKind::Codex, true);

    // Act
    observe_line(
        &observer,
        r#"{"type":"item.updated","item":{"type":"reasoning","text":"   "}}"#,
    );

    // Assert
    assert!(event_receiver.try_recv().is_err());
}

#[test]
fn test_build_command_request_uses_agent_facing_prompt_text() {
    // Arrange
    let request = TurnRequest {
        provider_call_budget: None,
        execution_policy: ag_contracts::ExecutionPolicy {
            max_concurrent_subagents: std::num::NonZeroUsize::new(7),
            ..ag_contracts::ExecutionPolicy::default()
        },
        continuation: ag_contracts::TurnContinuation::fresh(),
        folder: PathBuf::from("/tmp/session"),
        main_checkout_root: Some(PathBuf::from("/tmp/main")),
        model: "claude-sonnet-5-5".to_string(),
        permission_mode: ag_contracts::PermissionMode::AutoEdit,
        agent_profile: ag_contracts::AgentDefinitionPrompt::default(),
        prompt: TurnPrompt::from("Review @src/main.rs"),
        reasoning_level: ReasoningLevel::default(),
        request_kind: AgentRequestKind::SessionStart,
        response_style: ag_contracts::ResponseStyle::default(),
        speed_mode: ag_contracts::SpeedMode::default(),
    };
    let prompt_text = request.prompt.agent_text();

    // Act
    let build_request = build_command_request(&request, &prompt_text);

    // Assert
    assert_eq!(build_request.execution_policy, &request.execution_policy);
    assert_eq!(build_request.prompt, "Review \"src/main.rs\"");
    assert_eq!(
        build_request.main_checkout_root,
        Some(std::path::Path::new("/tmp/main"))
    );
}

#[tokio::test]
/// Verifies spawn failure returns `Err` with a descriptive message and
/// does not emit any turn events when the process never starts.
async fn test_run_turn_spawn_failure_returns_err_without_delta() {
    // Arrange
    let dir = tempdir().expect("failed to create temp dir");
    let mut mock_backend = MockAgentBackend::new();
    mock_backend
        .expect_build_command()
        .returning(|_| Ok(std::process::Command::new("/no-such-binary-agentty-test")));
    let channel = CliAgentChannel {
        active: Arc::default(),
        backend: Arc::new(mock_backend),
        kind: AgentKind::Claude,
        steering: TurnSteeringRegistry::default(),
    };
    let (events_tx, mut events_rx) = mpsc::unbounded_channel();
    let req = make_turn_request(dir.path().to_path_buf());

    // Act
    let result = channel.run_turn("sess-1".to_string(), req, events_tx).await;

    // Assert
    let error_message = result
        .expect_err("expected Err for spawn failure")
        .to_string();
    assert!(
        error_message.contains("Failed to spawn process"),
        "error was: {error_message}"
    );
    assert!(
        events_rx.try_recv().is_err(),
        "no events should be emitted when the process never spawned"
    );
}

#[tokio::test]
/// Verifies kill-by-signal returns `Err` with a `[Stopped]` message and
/// does not emit any loader updates.
async fn test_run_turn_kill_signal_returns_err_without_stopped_delta() {
    // Arrange
    let dir = tempdir().expect("failed to create temp dir");
    let mut mock_backend = MockAgentBackend::new();
    mock_backend.expect_build_command().returning(|_| {
        let mut cmd = std::process::Command::new("sh");
        cmd.arg("-c").arg("kill -9 $$");

        Ok(cmd)
    });
    let channel = CliAgentChannel {
        active: Arc::default(),
        backend: Arc::new(mock_backend),
        kind: AgentKind::Claude,
        steering: TurnSteeringRegistry::default(),
    };
    let (events_tx, mut events_rx) = mpsc::unbounded_channel();
    let req = make_turn_request(dir.path().to_path_buf());

    // Act
    let result = channel.run_turn("sess-1".to_string(), req, events_tx).await;

    // Assert
    let error_message = result
        .expect_err("expected Err for kill-by-signal")
        .to_string();
    assert!(
        error_message.contains("[Stopped]"),
        "error was: {error_message}"
    );

    // Drain `PidUpdate` events and verify no loader update was emitted.
    while let Ok(event) = events_rx.try_recv() {
        assert!(
            matches!(event, TurnEvent::PidUpdate(_)),
            "only PidUpdate events expected, got: {event:?}"
        );
    }
}

#[tokio::test]
/// Verifies that a clean process exit returns `Ok(TurnResult)` with no
/// context reset (CLI turns never reset context).
async fn test_run_turn_clean_exit_returns_ok_result_without_context_reset() {
    // Arrange
    let dir = tempdir().expect("failed to create temp dir");
    let mut mock_backend = MockAgentBackend::new();
    mock_backend.expect_build_command().returning(|_| {
        let mut command = std::process::Command::new("sh");
        command
            .arg("-c")
            .arg("printf '{\"answer\":\"ok\",\"questions\":[]}'");

        Ok(command)
    });
    let channel = CliAgentChannel {
        active: Arc::default(),
        backend: Arc::new(mock_backend),
        kind: AgentKind::Claude,
        steering: TurnSteeringRegistry::default(),
    };
    let (events_tx, _events_rx) = mpsc::unbounded_channel();
    let req = make_turn_request(dir.path().to_path_buf());

    // Act
    let result = channel.run_turn("sess-1".to_string(), req, events_tx).await;

    // Assert
    let turn_result = result.expect("expected Ok for clean exit");
    assert!(!turn_result.context_reset);
}

#[tokio::test]
/// Verifies Claude CLI turns avoid deadlock when the child emits stderr
/// before it starts reading a large stdin prompt.
async fn test_run_turn_writes_large_stdin_concurrently_for_claude() {
    // Arrange
    let dir = tempdir().expect("failed to create temp dir");
    let mut mock_backend = MockAgentBackend::new();
    mock_backend.expect_build_command().returning(|_| {
        let mut command = std::process::Command::new("sh");
        command.arg("-c").arg(
            "printf 'warming up\\n' >&2; sleep 0.1; head -n 1 >/dev/null; printf '%s' \
             '{\"answer\":\"ok\",\"questions\":[]}'",
        );

        Ok(command)
    });
    let channel = CliAgentChannel {
        active: Arc::default(),
        backend: Arc::new(mock_backend),
        kind: AgentKind::Claude,
        steering: TurnSteeringRegistry::default(),
    };
    let (events_tx, _events_rx) = mpsc::unbounded_channel();
    let mut req = make_turn_request(dir.path().to_path_buf());
    req.prompt = "x".repeat(512 * 1024).into();

    // Act
    let result = tokio::time::timeout(
        Duration::from_secs(5),
        channel.run_turn("sess-1".to_string(), req, events_tx),
    )
    .await
    .expect("turn should not deadlock")
    .expect("turn should succeed");

    // Assert
    assert_eq!(result.assistant_message.to_display_text(), "ok");
}

#[tokio::test]
/// Verifies Claude CLI turns stream image-aware prompt text through stdin
/// so large multimodal session prompts do not rely on argv transport.
async fn test_run_turn_writes_prompt_to_stdin_for_claude() {
    // Arrange
    let dir = tempdir().expect("failed to create temp dir");
    let capture_path = dir.path().join("stdin.txt");
    let image_path = dir.path().join("pasted-image.png");
    std::fs::write(&image_path, b"image-bytes").expect("image should be written");
    let mut mock_backend = MockAgentBackend::new();
    mock_backend.expect_build_command().returning({
        let capture_path = capture_path.clone();

        move |_| Ok(stdin_capture_command(&capture_path))
    });
    let channel = CliAgentChannel {
        active: Arc::default(),
        backend: Arc::new(mock_backend),
        kind: AgentKind::Claude,
        steering: TurnSteeringRegistry::default(),
    };
    let (events_tx, _events_rx) = mpsc::unbounded_channel();
    let mut req = make_turn_request(dir.path().to_path_buf());
    req.prompt = TurnPrompt {
        attachments: vec![TurnPromptAttachment {
            placeholder: "[Image #1]".to_string(),
            local_image_path: image_path.clone(),
        }],
        text: "Review [Image #1]".to_string(),
        text_source: TurnPromptTextSource::UserPrompt,
    };

    // Act
    let result = channel
        .run_turn("sess-1".to_string(), req, events_tx)
        .await
        .expect("turn should succeed");
    let captured_prompt =
        std::fs::read_to_string(&capture_path).expect("captured stdin payload should exist");

    // Assert
    assert_eq!(result.assistant_message.to_display_text(), "ok");
    assert!(captured_prompt.contains("Structured response protocol:"));
    assert!(captured_prompt.contains(image_path.to_string_lossy().as_ref()));
    assert!(!captured_prompt.contains("[Image #1]"));
}

#[tokio::test]
async fn resumed_claude_turn_delivers_legacy_instruction_withdrawal_over_stdin() {
    // Arrange
    let directory = tempdir_in(env!("CARGO_MANIFEST_DIR")).expect("capture directory");
    let capture_path = directory.path().join("stdin.txt");
    let mut backend = MockAgentBackend::new();
    backend.expect_build_command().times(1).returning({
        let capture_path = capture_path.clone();
        move |request| {
            let command = create_backend(AgentKind::Claude).build_command(request)?;
            assert!(command.get_args().any(|argument| argument == "-c"));

            Ok(stdin_capture_command(&capture_path))
        }
    });
    let channel = CliAgentChannel {
        active: Arc::default(),
        backend: Arc::new(backend),
        kind: AgentKind::Claude,
        steering: TurnSteeringRegistry::default(),
    };
    let mut request = make_turn_request(directory.path().to_path_buf());
    request.request_kind = AgentRequestKind::SessionResume;
    request.continuation = TurnContinuation::replaying("Earlier ordinary conversation".into());
    request.agent_profile = AgentDefinitionPrompt::cleared(true);
    let (events_tx, _events_rx) = mpsc::unbounded_channel();

    // Act
    let result = channel
        .run_turn("session".into(), request, events_tx)
        .await
        .expect("resumed turn");
    let stdin = std::fs::read_to_string(capture_path).expect("captured stdin");

    // Assert
    assert_eq!(result.assistant_message.to_display_text(), "ok");
    assert!(stdin.contains("Disregard previous personality and agent-profile instructions."));
    assert!(stdin.contains("Earlier ordinary conversation"));
    assert!(stdin.contains("Write a test"));
}

#[tokio::test]
/// Verifies a broken stdin pipe does not hide the backend stderr or exit
/// status when the CLI exits before consuming the full prompt.
async fn test_run_turn_preserves_child_error_after_broken_pipe() {
    // Arrange
    let dir = tempdir().expect("failed to create temp dir");
    let mut mock_backend = MockAgentBackend::new();
    mock_backend.expect_build_command().returning(|_| {
        let mut command = std::process::Command::new("sh");
        command.arg("-c").arg("printf 'auth failed' >&2; exit 9");

        Ok(command)
    });
    let channel = CliAgentChannel {
        active: Arc::default(),
        backend: Arc::new(mock_backend),
        kind: AgentKind::Claude,
        steering: TurnSteeringRegistry::default(),
    };
    let (events_tx, _events_rx) = mpsc::unbounded_channel();
    let mut req = make_turn_request(dir.path().to_path_buf());
    req.prompt = "x".repeat(512 * 1024).into();

    // Act
    let error = channel
        .run_turn("sess-1".to_string(), req, events_tx)
        .await
        .expect_err("turn should surface the child exit");

    // Assert
    let error_message = error.to_string();
    assert!(
        error_message.contains("auth failed"),
        "error was: {error_message}"
    );
    assert!(
        !error_message.contains("stdin payload"),
        "stdin write error should not mask child failure: {error_message}"
    );
}

#[tokio::test]
async fn cli_archive_failure_stops_before_spawning_provider() {
    // Arrange
    let folder = tempdir().expect("workspace");
    let backend = Arc::new(MockAgentBackend::new());
    let channel = CliAgentChannel::with_backend(backend, AgentKind::Claude);
    let mut request = make_turn_request(folder.path().join("missing"));
    request.continuation = ag_contracts::TurnContinuation::replaying("x".repeat(40 * 1024));
    let (events, _receiver) = mpsc::unbounded_channel();

    // Act
    let result = channel.run_turn("session".into(), request, events).await;

    // Assert
    assert!(result.is_err());
}

#[tokio::test]
/// Verifies non-zero CLI turn exits surface actionable Claude
/// re-authentication guidance instead of protocol schema errors.
async fn test_run_turn_returns_claude_auth_guidance_for_expired_token() {
    // Arrange
    let dir = tempdir().expect("failed to create temp dir");
    let mut mock_backend = MockAgentBackend::new();
    mock_backend.expect_build_command().times(1).returning(|_| {
        let mut command = std::process::Command::new("sh");
        command.arg("-c").arg(
            "printf '%s' \
             '{\"type\":\"error\",\"error\":{\"type\":\"authentication_error\",\"message\":\"\
             OAuth token has expired. Please obtain a new token or refresh your existing \
             token.\"}}'; exit 1",
        );

        Ok(command)
    });
    let channel = CliAgentChannel {
        active: Arc::default(),
        backend: Arc::new(mock_backend),
        kind: AgentKind::Claude,
        steering: TurnSteeringRegistry::default(),
    };
    let (events_tx, _events_rx) = mpsc::unbounded_channel();
    let req = make_turn_request(dir.path().to_path_buf());

    // Act
    let error_message = channel
        .run_turn("sess-1".to_string(), req, events_tx)
        .await
        .expect_err("expired Claude auth should fail")
        .to_string();

    // Assert
    assert!(error_message.contains("Agent command failed because Claude authentication expired"));
    assert!(error_message.contains("`claude auth login`"));
    assert!(error_message.contains("`claude auth status`"));
}

#[tokio::test]
/// Verifies non-zero CLI turn exits preserve generic stderr details for
/// non-authentication failures.
async fn test_run_turn_returns_exit_error_for_non_zero_status() {
    // Arrange
    let dir = tempdir().expect("failed to create temp dir");
    let mut mock_backend = MockAgentBackend::new();
    mock_backend.expect_build_command().times(1).returning(|_| {
        let mut command = std::process::Command::new("sh");
        command
            .arg("-c")
            .arg("printf '%s' 'assist failed' >&2; exit 7");

        Ok(command)
    });
    let channel = CliAgentChannel {
        active: Arc::default(),
        backend: Arc::new(mock_backend),
        kind: AgentKind::Claude,
        steering: TurnSteeringRegistry::default(),
    };
    let (events_tx, _events_rx) = mpsc::unbounded_channel();
    let req = make_turn_request(dir.path().to_path_buf());

    // Act
    let error_message = channel
        .run_turn("sess-1".to_string(), req, events_tx)
        .await
        .expect_err("non-zero exit should fail")
        .to_string();

    // Assert
    assert!(error_message.contains("Agent command failed with exit code 7"));
    assert!(error_message.contains("assist failed"));
}

#[tokio::test]
/// Verifies CLI channels surface only transient loader text while the
/// final assistant response is returned at turn completion.
async fn test_run_turn_surfaces_only_loader_updates_for_strict_protocol_provider() {
    // Arrange
    let dir = tempdir().expect("failed to create temp dir");
    let mut mock_backend = MockAgentBackend::new();
    mock_backend.expect_build_command().returning(|_| {
        let mut command = std::process::Command::new("sh");
        command.arg("-c").arg(concat!(
            r#"echo '{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","name":"Bash"}]}}';"#,
            r#"echo '{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"streamed fragment"}]}}';"#,
            r#"echo '{"result":"{\"answer\":\"final answer\",\"questions\":[]}","usage":{"input_tokens":5,"output_tokens":3}}'"#,
        ));

        Ok(command)
    });
    let channel = CliAgentChannel {
        active: Arc::default(),
        backend: Arc::new(mock_backend),
        kind: AgentKind::Claude,
        steering: TurnSteeringRegistry::default(),
    };
    let (events_tx, mut events_rx) = mpsc::unbounded_channel();
    let req = make_turn_request(dir.path().to_path_buf());

    // Act
    let result = channel
        .run_turn("sess-1".to_string(), req, events_tx)
        .await
        .expect("turn should succeed");

    // Assert
    let mut saw_loader_update = false;
    while let Ok(event) = events_rx.try_recv() {
        if matches!(event, TurnEvent::ThoughtDelta(_)) {
            saw_loader_update = true;
        }
    }
    assert!(saw_loader_update, "loader updates should be streamed live");
    assert_eq!(result.assistant_message.to_display_text(), "final answer");
}

#[tokio::test]
async fn claude_cli_activity_reports_skill_and_interrupted_tool() {
    // Arrange
    let directory = tempdir().expect("test fixture should succeed");
    let mut backend = MockAgentBackend::new();
    backend.expect_build_command().returning(|_| {
        let mut command = std::process::Command::new("sh");
        command.arg("-c").arg(r#"printf '%s\n' '{"type":"assistant","message":{"content":[{"type":"tool_use","id":"one","name":"Skill","input":{"skill":"review"}},{"type":"tool_use","id":"two","name":"Read"}]}}' '{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"one"}]}}' '{"type":"result","result":"{\"answer\":\"done\",\"questions\":[]}"}'"#);
        Ok(command)
    });
    let channel = CliAgentChannel::with_backend(Arc::new(backend), AgentKind::Claude);
    let (sender, mut receiver) = mpsc::unbounded_channel();

    // Act
    channel
        .run_turn(
            "session".into(),
            make_turn_request(directory.path().into()),
            sender,
        )
        .await
        .expect("test fixture should succeed");
    let mut activities = Vec::new();
    while let Some(event) = receiver.recv().await {
        if let TurnEvent::Activity(event) = event {
            activities.push(event);
        }
    }

    // Assert
    assert_eq!(activities.len(), 4);
    assert_eq!(activities[0].kind, ag_contracts::ActivityKind::Skill);
    assert_eq!(activities[0].name, "review");
    assert_eq!(
        activities[2].status,
        ag_contracts::ActivityStatus::Completed
    );
    assert_eq!(
        activities[3].status,
        ag_contracts::ActivityStatus::Interrupted
    );
}

#[test]
fn repair_activity_is_forwarded_without_private_loader_text() {
    // Arrange
    let (sender, mut receiver) = mpsc::unbounded_channel();
    let observer = CliTurnObserver::new(sender, AgentKind::Claude, false);

    // Act
    observe_line(
        &observer,
        r#"{"type":"assistant","message":{"content":[{"type":"tool_use","id":"call","name":"Read"},{"type":"text","text":"private repair text"}]}}"#,
    );
    drop(observer);
    let events = std::iter::from_fn(|| receiver.try_recv().ok()).collect::<Vec<_>>();

    // Assert
    assert_eq!(events.len(), 2);
    assert!(
        events
            .iter()
            .all(|event| matches!(event, TurnEvent::Activity(_)))
    );
}

#[test]
fn cli_turn_observer_keeps_activity_and_progress_framing_for_each_line_shape() {
    // Arrange
    let (sender, mut receiver) = mpsc::unbounded_channel();
    let observer = CliTurnObserver::new(sender, AgentKind::Claude, true);
    let tool_use = |id: &str| {
        format!(
            r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"{id}","name":"Bash"}}]}}}}"#
        )
    };

    // Act
    for line in [
        String::new(),
        "plain diagnostic text".to_string(),
        format!(" \t{}\t ", tool_use("json-whitespace")),
        format!("\u{a0}{}", tool_use("unicode-whitespace")),
        r#"{"type":"assistant","message":{"role":"assistant","content":"answer text"}}"#
            .to_string(),
    ] {
        observe_line(&observer, &line);
    }
    let events = std::iter::from_fn(|| receiver.try_recv().ok())
        .map(|event| match event {
            TurnEvent::Activity(activity) => {
                format!("activity {} {:?}", activity.id, activity.status)
            }
            TurnEvent::ThoughtDelta(text) => format!("thought {text}"),
            other => format!("{other:?}"),
        })
        .collect::<Vec<_>>();

    // Assert
    // Activity reads only lines that parse exactly, while stream progress
    // also accepts Unicode whitespace around the payload.
    assert_eq!(
        events,
        [
            "activity json-whitespace Running",
            "thought Running a command",
            "thought Running a command",
        ]
    );
}